const SAMPLE_COMPS = [
  { address: '215 Nacoochee Dr', price: 592000, sqft: 4800, ppsf: 123, beds: 4, baths: 3, dom: 28, dist: 0.3, year: 2003 },
  { address: '120 Oak Ridge Ct', price: 615000, sqft: 5100, ppsf: 121, beds: 5, baths: 4, dom: 41, dist: 0.6, year: 2005 },
  { address: '88 Laurel Springs', price: 578000, sqft: 4650, ppsf: 124, beds: 4, baths: 3, dom: 19, dist: 0.8, year: 2001 },
  { address: '305 Woodmont Way', price: 624000, sqft: 5250, ppsf: 119, beds: 5, baths: 4, dom: 52, dist: 1.1, year: 2007 },
  { address: '47 Riverstone Dr', price: 601000, sqft: 4950, ppsf: 121, beds: 4, baths: 3, dom: 33, dist: 1.3, year: 2004 },
];
const SAMPLE_TAX = [
  { year: 2024, total: 4850 }, { year: 2023, total: 4610 }, { year: 2022, total: 4380 }, { year: 2021, total: 4120 },
];
const SAMPLE_ASSESS = [
  { year: 2024, value: 412000, land: 95000, improvements: 317000 },
  { year: 2023, value: 388000, land: 90000, improvements: 298000 },
];

function CompsTab({ deal, calc, update }) {
  const [loading, setLoading] = React.useState(false);
  const [status, setStatus] = React.useState(null);
  const c = deal.comps && deal.comps.list && deal.comps.list.length ? deal.comps : { list: SAMPLE_COMPS, avgPrice: 602000, avgPpsf: 122, avgDom: 35, source: 'sample' };
  const taxes = deal.taxRecords && deal.taxRecords.length ? deal.taxRecords : SAMPLE_TAX;
  const assess = deal.taxAssess && deal.taxAssess.length ? deal.taxAssess : SAMPLE_ASSESS;
  const isSample = !(deal.comps && deal.comps.source === 'live');

  const annualRent = (deal.capRate.monthlyRent || 0) * 12;
  const grossYield = deal.terms.sellingPrice ? (annualRent / deal.terms.sellingPrice) * 100 : 0;
  const arvFromComps = c.avgPpsf && deal.property.sqft ? c.avgPpsf * deal.property.sqft : c.avgPrice;

  const addr = [deal.property.address, deal.property.city, deal.property.state, deal.property.zip].filter(Boolean).join(', ');

  const pull = async () => {
    setLoading(true); setStatus(null);
    const [cmp, prop] = await Promise.all([fetchComps(addr), fetchProperty(addr)]);
    const patch = {};
    if (cmp.ok && cmp.comps.length) {
      patch.comps = { list: cmp.comps, avgPrice: cmp.avgPrice, avgPpsf: cmp.avgPpsf, avgDom: cmp.avgDom, source: 'live' };
    }
    if (prop.ok && (prop.taxes.length || prop.assess.length)) {
      patch.taxRecords = prop.taxes; patch.taxAssess = prop.assess;
    }
    if (Object.keys(patch).length) { update(patch); setStatus({ ok: true, msg: 'Live data pulled from RentCast' }); }
    else setStatus({ ok: false, msg: rentcastHint((cmp.error || prop.error)) });
    setLoading(false);
  };

  return (
    <div>
      <div className="comps-head">
        <div>
          <h2 className="tab-title">Comparable Sales &amp; ARV</h2>
          <div className="tab-desc">Recent nearby sales used to triangulate after-repair value.</div>
        </div>
        <button className="btn primary" onClick={pull} disabled={loading}>
          {loading ? <span className="spin"></span> : <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M21 12a9 9 0 1 1-9-9" /><path d="M21 3v6h-6" /></svg>}
          {loading ? 'Pulling…' : 'Pull comps'}
        </button>
      </div>
      {status ? <div className={'fetch-status ' + (status.ok ? 'ok' : 'warn')} style={{ marginBottom: 16 }}><div className="fs-msg">{status.msg}</div></div> : null}

      <AIARVSuggester deal={deal} update={update} />

      <div className="kpi-strip" style={{ marginTop: 0 }}>
        <div className="kpi accent"><div className="l">Avg Comp Price</div><div className="v">{fmtMoney(c.avgPrice)}</div><div className="hint">{c.list.length} comps · {isSample ? 'sample' : 'live'}</div></div>
        <div className="kpi"><div className="l">Avg $/Sq Ft</div><div className="v">{fmtMoney(c.avgPpsf)}</div><div className="hint">ARV ≈ {fmtMoney(arvFromComps)}</div></div>
        <div className="kpi"><div className="l">Avg Days on Market</div><div className="v">{c.avgDom} <span style={{ fontSize: 14, color: 'var(--muted)' }}>days</span></div><div className="hint">Liquidity signal</div></div>
        <div className="kpi"><div className="l">Gross Rent Yield</div><div className="v">{fmtPct(grossYield)}</div><div className="hint">{fmtMoney(annualRent)}/yr on ARV</div></div>
      </div>

      <div className="card" style={{ marginTop: 16 }}>
        <div className="card-head"><h3>Comparable Sales</h3>
          <button className="use-btn" onClick={() => update({ terms: { ...deal.terms, sellingPrice: Math.round(arvFromComps) } })}>Use $/sqft ARV → {fmtMoney(arvFromComps)}</button>
        </div>
        <div className="card-body" style={{ padding: 0 }}>
          <table className="cmp-tbl comps">
            <thead><tr><th>Address</th><th>Price</th><th>Sq Ft</th><th>$/Sq Ft</th><th>Bd/Ba</th><th>DOM</th><th>Dist</th></tr></thead>
            <tbody>
              {c.list.map((x, i) => (
                <tr key={i}>
                  <td>{x.address}</td><td>{fmtMoney(x.price)}</td><td>{fmtNum(x.sqft)}</td>
                  <td>{fmtMoney(x.ppsf)}</td><td>{x.beds}/{x.baths}</td><td>{x.dom != null ? x.dom : '—'}</td>
                  <td>{x.dist != null ? x.dist + ' mi' : '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <ManualComps deal={deal} update={update} />

      <div className="two-col" style={{ marginTop: 16 }}>
        <div className="card">
          <div className="card-head"><h3>Property Tax Records</h3><span className={'src-pill ' + (deal.taxRecords && deal.taxRecords.length ? 'live' : 'sample')}>{deal.taxRecords && deal.taxRecords.length ? 'Live' : 'Sample'}</span></div>
          <div className="card-body" style={{ padding: 0 }}>
            <table className="cmp-tbl"><thead><tr><th>Year</th><th>Tax Paid</th><th>YoY</th></tr></thead>
              <tbody>
                {taxes.map((t, i) => {
                  const prev = taxes[i + 1];
                  const yoy = prev && prev.total ? ((t.total - prev.total) / prev.total) * 100 : null;
                  return <tr key={i}><td>{t.year}</td><td>{fmtMoney(t.total)}</td><td className={yoy > 0 ? 'bad-c' : 'good-c'}>{yoy == null ? '—' : (yoy > 0 ? '+' : '') + fmtPct(yoy)}</td></tr>;
                })}
              </tbody>
            </table>
          </div>
        </div>
        <div className="card">
          <div className="card-head"><h3>Assessed Value</h3><span className={'src-pill ' + (deal.taxAssess && deal.taxAssess.length ? 'live' : 'sample')}>{deal.taxAssess && deal.taxAssess.length ? 'Live' : 'Sample'}</span></div>
          <div className="card-body" style={{ padding: 0 }}>
            <table className="cmp-tbl"><thead><tr><th>Year</th><th>Total</th><th>Land</th><th>Improvements</th></tr></thead>
              <tbody>
                {assess.map((a, i) => (
                  <tr key={i}><td>{a.year}</td><td>{fmtMoney(a.value)}</td><td>{fmtMoney(a.land)}</td><td>{fmtMoney(a.improvements)}</td></tr>
                ))}
              </tbody>
            </table>
            <div style={{ padding: '10px 14px', fontSize: 11.5, color: 'var(--muted)', lineHeight: 1.5 }}>Assessed value is typically below market — useful for spotting tax reassessment risk after purchase.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.CompsTab = CompsTab;

/* ============ Manual comp entry + auto ARV ============ */
const BLANK_COMP = { address: '', city: '', zip: '', price: 0, sqft: 0, beds: 0, baths: 0, year: '', dom: '', saleDate: '', distance: '', condition: 'Similar', notes: '' };
const CONDITION_ADJ = { Better: 0.97, Similar: 1, Worse: 1.03 };

function ManualComps({ deal, update }) {
  const [form, setForm] = React.useState({ ...BLANK_COMP });
  const list = deal.manualComps || [];
  const setF = (k, v) => setForm((s) => ({ ...s, [k]: v }));
  const subjSqft = deal.property.sqft || 0;

  const add = () => {
    if (!form.address && !form.price) return;
    update({ manualComps: [...list, { ...form }] });
    setForm({ ...BLANK_COMP });
  };
  const remove = (i) => update({ manualComps: list.filter((_, idx) => idx !== i) });

  const valid = list.filter((c) => Number(c.price) > 0);
  const prices = valid.map((c) => Number(c.price));
  const ppsfs = valid.filter((c) => Number(c.sqft) > 0).map((c) => Number(c.price) / Number(c.sqft));
  const adjPpsfs = valid.filter((c) => Number(c.sqft) > 0).map((c) => (Number(c.price) / Number(c.sqft)) * (CONDITION_ADJ[c.condition] || 1));
  const mean = (a) => a.length ? a.reduce((x, y) => x + y, 0) / a.length : 0;
  const avgPrice = mean(prices);
  const avgPpsf = mean(ppsfs);
  const adjAvgPpsf = mean(adjPpsfs);
  const hi = prices.length ? Math.max(...prices) : 0;
  const lo = prices.length ? Math.min(...prices) : 0;
  const suggestedARV = adjAvgPpsf && subjSqft ? Math.round(adjAvgPpsf * subjSqft) : Math.round(avgPrice);

  const Cell = ({ k, w, ph, type }) => (
    type === 'money' ? <MoneyInput value={form[k]} onChange={(v) => setF(k, v)} />
    : <input className="mc-in" style={w ? { width: w } : null} placeholder={ph} value={form[k]} onChange={(e) => setF(k, e.target.value)} />
  );

  return (
    <div className="card" style={{ marginTop: 16 }}>
      <div className="card-head"><h3>Your Comps &mdash; Manual Entry</h3>
        {valid.length ? <span className="head-total">{valid.length} comp{valid.length > 1 ? 's' : ''}</span> : null}
      </div>
      <div className="card-body">
        <div style={{ fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.5, marginBottom: 12 }}>
          Add your own comparables. $/sqft auto-calculates; condition adjusts the ARV (Better comps pull ARV down, Worse pull it up).
        </div>

        <div className="mc-form">
          <div className="mc-field" style={{ gridColumn: 'span 2' }}><label>Address</label><input className="mc-in" value={form.address} onChange={(e) => setF('address', e.target.value)} placeholder="123 Main St" /></div>
          <div className="mc-field"><label>City</label><input className="mc-in" value={form.city} onChange={(e) => setF('city', e.target.value)} /></div>
          <div className="mc-field"><label>ZIP</label><input className="mc-in" value={form.zip} onChange={(e) => setF('zip', e.target.value)} /></div>
          <div className="mc-field"><label>Sale price</label><MoneyInput value={form.price} onChange={(v) => setF('price', v)} /></div>
          <div className="mc-field"><label>Sq ft</label><input className="mc-in" inputMode="numeric" value={form.sqft} onChange={(e) => setF('sqft', e.target.value.replace(/[^0-9]/g, ''))} /></div>
          <div className="mc-field"><label>$/sqft</label><div className="mc-calc">{form.sqft && form.price ? fmtMoney(form.price / form.sqft) : '—'}</div></div>
          <div className="mc-field"><label>Beds</label><input className="mc-in" value={form.beds} onChange={(e) => setF('beds', e.target.value)} /></div>
          <div className="mc-field"><label>Baths</label><input className="mc-in" value={form.baths} onChange={(e) => setF('baths', e.target.value)} /></div>
          <div className="mc-field"><label>Year built</label><input className="mc-in" value={form.year} onChange={(e) => setF('year', e.target.value)} /></div>
          <div className="mc-field"><label>Days on mkt</label><input className="mc-in" value={form.dom} onChange={(e) => setF('dom', e.target.value)} /></div>
          <div className="mc-field"><label>Sale date</label><input className="mc-in" type="date" value={form.saleDate} onChange={(e) => setF('saleDate', e.target.value)} /></div>
          <div className="mc-field"><label>Distance (mi)</label><input className="mc-in" value={form.distance} onChange={(e) => setF('distance', e.target.value)} /></div>
          <div className="mc-field"><label>Condition</label>
            <select className="mc-in" value={form.condition} onChange={(e) => setF('condition', e.target.value)}><option>Similar</option><option>Better</option><option>Worse</option></select>
          </div>
          <div className="mc-field" style={{ gridColumn: 'span 2' }}><label>Notes</label><input className="mc-in" value={form.notes} onChange={(e) => setF('notes', e.target.value)} /></div>
          <div className="mc-field mc-addwrap"><label>&nbsp;</label><button className="btn primary" onClick={add}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 5v14M5 12h14" /></svg>Add</button></div>
        </div>

        {valid.length ? (
          <React.Fragment>
            <div className="sched-scroll" style={{ marginTop: 14, maxHeight: 300 }}>
              <table className="cmp-tbl comps">
                <thead><tr><th>Address</th><th>Price</th><th>Sq Ft</th><th>$/Sq Ft</th><th>Cond.</th><th>DOM</th><th>Dist</th><th></th></tr></thead>
                <tbody>
                  {list.map((c, i) => Number(c.price) > 0 ? (
                    <tr key={i}>
                      <td>{c.address || '—'}{c.notes ? <span style={{ display: 'block', fontSize: 11, color: 'var(--muted)', fontWeight: 400 }}>{c.notes}</span> : null}</td>
                      <td>{fmtMoney(c.price)}</td><td>{c.sqft ? fmtNum(c.sqft) : '—'}</td>
                      <td>{c.sqft ? fmtMoney(c.price / c.sqft) : '—'}</td>
                      <td>{c.condition}</td><td>{c.dom || '—'}</td><td>{c.distance ? c.distance + ' mi' : '—'}</td>
                      <td><button className="row-del" onClick={() => remove(i)}>✕</button></td>
                    </tr>
                  ) : null)}
                </tbody>
              </table>
            </div>

            <div className="mc-summary">
              <div className="mc-stat"><div className="l">Avg sale price</div><div className="v">{fmtMoney(avgPrice)}</div></div>
              <div className="mc-stat"><div className="l">Avg $/sqft</div><div className="v">{fmtMoney(avgPpsf)}</div></div>
              <div className="mc-stat"><div className="l">Range</div><div className="v" style={{ fontSize: 16 }}>{fmtMoney(lo)} – {fmtMoney(hi)}</div></div>
              <div className="mc-stat"><div className="l">Adjusted ARV · {fmtNum(subjSqft)} sqft</div><div className="v" style={{ color: 'var(--green-700)' }}>{fmtMoney(suggestedARV)}</div></div>
            </div>
            <button className="btn primary" style={{ marginTop: 12 }} onClick={() => update({ terms: { ...deal.terms, sellingPrice: suggestedARV } })}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
              Use suggested ARV → {fmtMoney(suggestedARV)} (syncs to deal)
            </button>
          </React.Fragment>
        ) : <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 6 }}>No comps added yet. Fill the row above and click Add.</div>}
      </div>
    </div>
  );
}

window.ManualComps = ManualComps;
