function Summary({ deal, calc, update, updateList, listApi }) {
  const t = deal.terms;
  const p = deal.property;

  const setTerm = (k, v) => update({ terms: { ...t, [k]: v } });
  const setProp = (k, v) => update({ property: { ...p, [k]: v } });

  return (
    <div>
      <AddressLookup deal={deal} update={update} />

      <div className="deal-summary-row">
        <div className="deal-summary-card">
          <div className="deal-summary-label">Accepted Price</div>
          <div className="deal-summary-value">
            <MoneyInput value={t.acceptedPrice} onChange={(v) => setTerm('acceptedPrice', v)} />
          </div>
        </div>
        <div className="deal-summary-card">
          <div className="deal-summary-label">Selling Price / ARV</div>
          <div className="deal-summary-value">
            <MoneyInput value={t.sellingPrice} onChange={(v) => setTerm('sellingPrice', v)} />
          </div>
        </div>
        <div className="deal-summary-card">
          <div className="deal-summary-label">Suggested Max Offer</div>
          <div className="deal-summary-value">
            {fmtMoney(calc.mao)}
          </div>
          <div className="deal-summary-note">70% rule</div>
        </div>
        <div className="deal-summary-card">
          <div className="deal-summary-label">Offer Gap</div>
          <div className={"deal-summary-value " + (t.acceptedPrice <= calc.mao ? 'pos' : 'neg')}>
            {fmtMoney(calc.mao - t.acceptedPrice)}
          </div>
          <div className="deal-summary-note">{t.acceptedPrice <= calc.mao ? 'Under MAO' : 'Above MAO'}</div>
        </div>
      </div>
      <div className="offer-guidance-box">
        <div className="offer-guidance-title">Offer Guidance</div>
        <div className="offer-guidance-copy">Edit your accepted price and expected sale ARV in one place, then use the market estimates below to check the deal and apply the best price.</div>
      </div>

      <MarketPanel deal={deal} calc={calc} update={update} />

      <AIDealScore deal={deal} calc={calc} />

      <div className="grid">
        {/* ---------- LEFT: property ---------- */}
        <div className="col">
          <div className="card">
            <div className="card-head"><h3>Property</h3></div>
            <div className="prop-photo">
              {p.photoUrl ? (
                <div style={{ position: 'relative' }}>
                  <img src={p.photoUrl} alt="property" style={{ width: '100%', height: 184, objectFit: 'cover', display: 'block' }} onError={(e) => { e.target.style.display = 'none'; }} />
                  <button className="photo-clear" onClick={() => setProp('photoUrl', '')} title="Remove photo">✕</button>
                </div>
              ) : (
                <image-slot id="prop-photo" shape="rect" placeholder="Drop a photo or paste a URL below" fit="cover"></image-slot>
              )}
            </div>
            <div className="card-body">
              <div className="photo-url">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1" /><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1" /></svg>
                <input value={p.photoUrl} placeholder="Paste a listing photo URL" onChange={(e) => setProp('photoUrl', e.target.value)} />
              </div>
              {p.lat ? (
                <div className="photo-toggle">
                  <button className={streetViewUrl(p.lat, p.lon) && p.photoUrl === streetViewUrl(p.lat, p.lon) ? 'on' : ''} onClick={() => setProp('photoUrl', streetViewUrl(p.lat, p.lon))} disabled={!streetViewUrl(p.lat, p.lon)} title={streetViewUrl(p.lat, p.lon) ? '' : 'Add a Google key in Settings'}>Street View</button>
                  <button className={p.photoUrl === staticMapUrl(p.lat, p.lon) ? 'on' : ''} onClick={() => setProp('photoUrl', staticMapUrl(p.lat, p.lon))}>Satellite</button>
                </div>
              ) : null}
              <div className="listing-links">
                {(() => { const L = buildListingLinks(p); return [
                  ['Zillow', L.zillow, '#1277e1'], ['Redfin', L.redfin, '#d4502e'],
                  ['Realtor', L.realtor, '#c8102e'], ['Homes', L.homes, '#1c7d6f'],
                ].map(([n, u, col]) => (
                  <a key={n} className="listing-link" href={u} target="_blank" rel="noopener noreferrer">
                    <span className="ll-dot" style={{ background: col }}></span>{n}
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17L17 7M9 7h8v8" /></svg>
                  </a>
                )); })()}
              </div>
              <div className="kv">
                <div className="frow-label">Address</div><TextInput value={p.address} onChange={(v) => setProp('address', v)} align="right" wide />
                <div className="frow-label">City</div><TextInput value={p.city} onChange={(v) => setProp('city', v)} align="right" />
                <div className="frow-label">State</div><TextInput value={p.state} onChange={(v) => setProp('state', v)} align="right" />
                <div className="frow-label">Zip</div><TextInput value={p.zip} onChange={(v) => setProp('zip', v)} align="right" />
                <div className="frow-label">MLS ID</div><TextInput value={p.mls} onChange={(v) => setProp('mls', v)} align="right" />
              </div>
              <div className="stat-mini" style={{ marginTop: 12 }}>
                <div className="cell"><div className="l">Size</div><div className="v tnum"><NumInput value={p.sqft} onChange={(v) => setProp('sqft', v || 0)} /> <span style={{ fontSize: 12, color: 'var(--muted)' }}>ft²</span></div></div>
                <div className="cell"><div className="l">Lot</div><div className="v tnum"><NumInput value={p.lotSize} onChange={(v) => setProp('lotSize', v || 0)} /> <span style={{ fontSize: 12, color: 'var(--muted)' }}>ac</span></div></div>
                <div className="cell"><div className="l">Beds</div><div className="v tnum"><NumInput value={p.beds} onChange={(v) => setProp('beds', v || 0)} /></div></div>
                <div className="cell"><div className="l">Baths</div><div className="v tnum"><NumInput value={p.baths} onChange={(v) => setProp('baths', v || 0)} /></div></div>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h3>Deal Terms</h3></div>
            <div className="card-body">
              <FeeRow label="Asking Price" value={t.askingPrice} onChange={(v) => setTerm('askingPrice', v)} />
              <div className="frow"><div className="frow-label">Asking / Sq Ft</div><div className="in zero" style={{ width: 118, textAlign: 'right' }}>{fmtMoney(calc.askPerSqft, 2)}</div></div>
              <FeeRow label="Offer Price" value={t.offerPrice} onChange={(v) => setTerm('offerPrice', v)} />
              <FeeRow label="Accepted Price" value={t.acceptedPrice} onChange={(v) => setTerm('acceptedPrice', v)} highlight />
              <div className="frow"><div className="frow-label">Accept / Sq Ft</div><div className="in zero" style={{ width: 118, textAlign: 'right' }}>{fmtMoney(calc.acceptPerSqft, 2)}</div></div>
              <div className="frow in-highlight">
                <div className="frow-label">Purchase Type</div>
                <select className="in" value={t.purchaseType} onChange={(e) => setTerm('purchaseType', e.target.value)}>
                  <option>Loan</option><option>Cash</option><option>Hard Money</option>
                </select>
              </div>
              <div className="frow"><div className="frow-label">Rehab Time</div><NumInput value={t.rehabMonths} onChange={(v) => setTerm('rehabMonths', v || 0)} suffix="months" /></div>
              <div className="frow"><div className="frow-label">Time on Market</div><NumInput value={t.marketMonths} onChange={(v) => setTerm('marketMonths', v || 0)} suffix="months" /></div>
              <div className="frow"><div className="frow-label">Holding Period<small>Months of carry cost</small></div><NumInput value={t.holdingMonths} onChange={(v) => setTerm('holdingMonths', v || 0)} suffix="months" /></div>
              <div className="frow"><div className="frow-label">Monthly Carry<small>{t.purchaseType === 'Cash' ? 'Cash purchase' : 'From mortgage calc'}</small></div><div className="in zero" style={{ width: 118, textAlign: 'right' }}>{fmtMoney(calc.monthlyHolding)}</div></div>
            </div>
          </div>
        </div>

        {/* ---------- MIDDLE: purchase + selling ---------- */}
        <div className="col">
          <div className="card">
            <div className="card-head"><h3>Purchase Costs &amp; Fees</h3><span className="head-total">{fmtMoney(calc.purchaseFeesSum)} <span className="head-pct">{t.acceptedPrice ? (calc.purchaseFeesSum / t.acceptedPrice * 100).toFixed(1) + '% of price' : ''}</span> <button className="sec-reset" title="Reset this table" onClick={() => listApi.resetList('purchaseFees')}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7L3 8" /><path d="M3 3v5h5" /></svg></button></span></div>
            <div className="card-body">
              {deal.purchaseFees.map((f, i) => (
                f.custom ? (
                  <div className="frow custom-row" key={i}>
                    <input className="in txt custom-label" value={f.k} onChange={(e) => listApi.renameItem('purchaseFees', i, e.target.value)} placeholder="Item name" />
                    <div className="frow-right">
                      {t.acceptedPrice ? <span className="pct-chip">{(f.v / t.acceptedPrice * 100).toFixed(1)}%</span> : null}
                      <MoneyInput value={f.v} onChange={(v) => updateList('purchaseFees', i, v)} />
                      <button className="row-del" title="Remove" onClick={() => listApi.removeItem('purchaseFees', i)}>✕</button>
                    </div>
                  </div>
                ) : (
                  <FeeRow key={i} label={f.k} value={f.v} onChange={(v) => updateList('purchaseFees', i, v)} pctOf={t.acceptedPrice} />
                )
              ))}
              <button className="add-row" onClick={() => listApi.addItem('purchaseFees', '')}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 5v14M5 12h14" /></svg>
                Add custom cost
              </button>
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h3>Selling Costs &amp; Fees</h3><span className="head-total">{fmtMoney(calc.sellingFeesSum)} <span className="head-pct">{t.sellingPrice ? (calc.sellingFeesSum / t.sellingPrice * 100).toFixed(1) + '% of ARV' : ''}</span> <button className="sec-reset" title="Reset this table" onClick={() => listApi.resetList('sellingFees')}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7L3 8" /><path d="M3 3v5h5" /></svg></button></span></div>
            <div className="card-body">
              <FeeRow label="Selling Price (ARV)" value={t.sellingPrice} onChange={(v) => setTerm('sellingPrice', v)} highlight />
              {deal.sellingFees.map((f, i) => (
                f.custom ? (
                  <div className="frow custom-row" key={i}>
                    <input className="in txt custom-label" value={f.k} onChange={(e) => listApi.renameItem('sellingFees', i, e.target.value)} placeholder="Item name" />
                    <div className="frow-right">
                      {t.sellingPrice ? <span className="pct-chip">{(f.v / t.sellingPrice * 100).toFixed(1)}%</span> : null}
                      <MoneyInput value={f.v} onChange={(v) => updateList('sellingFees', i, v)} />
                      <button className="row-del" title="Remove" onClick={() => listApi.removeItem('sellingFees', i)}>✕</button>
                    </div>
                  </div>
                ) : (
                  <FeeRow key={i} label={f.k} value={f.v} onChange={(v) => updateList('sellingFees', i, v)} pctOf={t.sellingPrice} />
                )
              ))}
              <button className="add-row" onClick={() => listApi.addItem('sellingFees', '')}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 5v14M5 12h14" /></svg>
                Add custom cost
              </button>
            </div>
          </div>
        </div>

        {/* ---------- RIGHT: rehab + charts ---------- */}
        <div className="col span-charts">
          <div className="card">
            <div className="card-head"><h3>Rehab Costs</h3><span className="head-total">{fmtMoney(calc.rehabSum)} <span className="head-pct">{t.sellingPrice ? (calc.rehabSum / t.sellingPrice * 100).toFixed(1) + '% of ARV' : ''}</span> <AIRehabButton deal={deal} update={update} /> <button className="sec-reset" title="Reset this table" onClick={() => listApi.resetList('rehab')}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7L3 8" /><path d="M3 3v5h5" /></svg></button></span></div>
            <div className="card-body">
              {deal.rehab.map((f, i) => (
                f.custom ? (
                  <div className="frow custom-row" key={i}>
                    <input className="in txt custom-label" value={f.k} onChange={(e) => listApi.renameItem('rehab', i, e.target.value)} placeholder="Item name" />
                    <div className="frow-right">
                      {t.sellingPrice ? <span className="pct-chip">{(f.v / t.sellingPrice * 100).toFixed(1)}%</span> : null}
                      <MoneyInput value={f.v} onChange={(v) => updateList('rehab', i, v)} />
                      <button className="row-del" title="Remove" onClick={() => listApi.removeItem('rehab', i)}>✕</button>
                    </div>
                  </div>
                ) : (
                  <FeeRow key={i} label={f.k} value={f.v} onChange={(v) => updateList('rehab', i, v)} pctOf={t.sellingPrice} />
                )
              ))}
              <button className="add-row" onClick={() => listApi.addItem('rehab', '')}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 5v14M5 12h14" /></svg>
                Add custom rehab item
              </button>
            </div>
          </div>

          <div className="card chart-card">
            <div className="card-head"><h3>Rehab Cost Breakdown</h3></div>
            <div className="card-body"><RehabDonut items={deal.rehab} total={calc.rehabSum} /></div>
          </div>

          <div className="card chart-card">
            <div className="card-head"><h3>Cost &amp; Profit Breakdown</h3></div>
            <div className="card-body">
              <CostBars rows={[
                { label: 'Purchase Price', value: t.acceptedPrice, color: 'var(--green-800)' },
                { label: 'Purchase Costs', value: calc.purchaseFeesSum, color: 'var(--green-600)' },
                { label: 'Rehab Costs', value: calc.rehabTotal, color: 'var(--sage-line)' },
                { label: 'Holding Cost', value: calc.holdingCost, color: '#9fb0a6' },
                { label: 'Selling Costs', value: calc.sellingFeesSum, color: 'var(--green-700)' },
                { label: 'Net Profit', value: calc.netProfit, color: calc.netProfit >= 0 ? '#6ea27f' : 'var(--coral)' },
              ]} />
            </div>
          </div>
        </div>
      </div>

      {/* ---------- Totals ---------- */}
      <div className="totals-row">
        <div className="total-chip"><span className="l">Purchase Total</span><span className="v">{fmtMoney(calc.purchaseTotal)}</span></div>
        <div className="total-chip"><span className="l">Rehab Total</span><span className="v">{fmtMoney(calc.rehabTotal)}</span></div>
        <div className="total-chip"><span className="l">Net Sale Price</span><span className="v">{fmtMoney(calc.netSalePrice)}</span></div>
      </div>

      {/* ---------- Profit ---------- */}
      <div className="profit-grid">
        <div className={'profit-card' + (calc.netProfit >= calc.profitGoal ? ' good' : '')}>
          <div className="pc-head">Net Profit</div>
          <div className="pc-big">{fmtMoney(calc.netProfit)}</div>
          <div className="pc-goal-label">Profit Goal · {t.profitGoalPct}% of purchase</div>
          <div className="pc-goal-val">
            {fmtMoney(calc.profitGoal)}
            <div className={'delta ' + (calc.netProfit - calc.profitGoal >= 0 ? 'pos' : 'neg')}>
              {calc.netProfit - calc.profitGoal >= 0 ? '▲ ' : '▼ '}{fmtMoney(Math.abs(calc.netProfit - calc.profitGoal))} vs goal
            </div>
          </div>
        </div>
        <div className={'profit-card' + (calc.netMargin >= calc.marginGoal ? ' good' : '')}>
          <div className="pc-head">Net Profit Margin</div>
          <div className="pc-big">{fmtPct(calc.netMargin)}</div>
          <div className="pc-goal-label">
            Margin Goal
            <input className="in" style={{ width: 64, marginLeft: 8, textAlign: 'center', background: 'var(--sage-soft)' }}
              value={t.profitGoalPct} onChange={(e) => setTerm('profitGoalPct', parseFloat(e.target.value.replace(/[^0-9.]/g, '')) || 0)} />
            <span style={{ fontSize: 14, marginLeft: 2 }}>%</span>
          </div>
          <div className="pc-goal-val">
            {fmtPct(calc.marginGoal)}
            <div className={'delta ' + (calc.netMargin - calc.marginGoal >= 0 ? 'pos' : 'neg')}>
              {calc.netMargin - calc.marginGoal >= 0 ? '▲ on target' : '▼ ' + fmtPct(Math.abs(calc.netMargin - calc.marginGoal)) + ' short'}
            </div>
          </div>
        </div>
      </div>

      {/* ---------- KPI strip ---------- */}
      <div className="kpi-strip">
        <div className="kpi accent">
          <div className="l">Return on Investment</div>
          <div className={'v' + (calc.roi < 0 ? ' neg' : '')}>{fmtPct(calc.roi)}</div>
          <div className="hint">Profit ÷ all-in cost</div>
        </div>
        <div className="kpi">
          <div className="l">All-In Cost</div>
          <div className="v">{fmtMoney(calc.allInCost)}</div>
          <div className="hint">Purchase + rehab + carry</div>
        </div>
        <div className="kpi">
          <div className="l">Max Offer · 70% Rule</div>
          <div className={'v' + (t.acceptedPrice > calc.mao ? ' neg' : '')}>{fmtMoney(calc.mao)}</div>
          <div className="hint">70% × ARV − rehab</div>
        </div>
        <div className="kpi">
          <div className="l">Holding Cost</div>
          <div className="v">{fmtMoney(calc.holdingCost)}</div>
          <div className="hint">{fmtMoney(calc.monthlyHolding)}/mo × {t.holdingMonths}</div>
        </div>
      </div>

      <div className="two-col" style={{ marginTop: 16 }}>
        <EstimateList
          title="Value Estimates · ARV"
          subtitle="Compare AVM estimates from each source. Edit any value or use the average as your After Repair Value."
          items={deal.estimates} listKey="estimates" updateList={updateList}
          avgLabel="Average estimate" useLabel="Use avg as ARV →"
          onUse={(v) => setTerm('sellingPrice', v)} />
        <EstimateList
          title="Rental Value"
          subtitle="Monthly rent estimates for buy-&-hold analysis. Feeds the Cap Rate tab."
          items={deal.rental} listKey="rental" suffix="/mo" updateList={updateList}
          avgLabel="Average rent" useLabel="Use as rent →"
          onUse={(v) => update({ capRate: { ...deal.capRate, monthlyRent: v } })} />
      </div>
    </div>
  );
}

window.Summary = Summary;
