/* ============ Rental AI Scoring ============ */
function RentalAIScore({ deal, rentalMetrics }) {
  const [loading, setLoading] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [error, setError] = React.useState('');

  const score = async () => {
    setLoading(true);
    setError('');
    setResult(null);
    const summary = `
Rental Property: ${deal.property.address}, ${deal.property.city}, ${deal.property.state}
Purchase Price: $${rentalMetrics.purchasePrice.toLocaleString()}
Monthly Rent: $${rentalMetrics.monthlyRent.toLocaleString()}
Annual NOI: $${Math.round(rentalMetrics.noi).toLocaleString()}
Cap Rate: ${rentalMetrics.capRate.toFixed(2)}%
Cash-on-Cash Return: ${rentalMetrics.cashOnCash.toFixed(2)}%
DSCR: ${rentalMetrics.dscr.toFixed(2)}x
Annual Cash Flow: $${Math.round(rentalMetrics.cashFlow).toLocaleString()}
Vacancy Rate: ${rentalMetrics.vacancyRate}%
Hold Period: ${rentalMetrics.holdingYears.toFixed(1)} years
Total Return: $${Math.round(rentalMetrics.totalReturn).toLocaleString()}
ROI: ${rentalMetrics.roi.toFixed(2)}%
Sqft: ${deal.property.sqft}, Beds: ${deal.property.beds}, Baths: ${deal.property.baths}
    `.trim();

    const systemPrompt = `You are an expert buy-and-hold real estate investment analyst. Score rental deals based on cash flow, cap rate, DSCR, cash-on-cash return, and long-term ROI. Be direct and data-driven.`;
    const prompt = `${summary}\n\nScore this rental deal from 1 (terrible) to 10 (excellent). Respond ONLY with minified JSON:\n{"score":<1-10>,"verdict":"<3-5 words>","summary":"<one sentence>","strengths":["<point>","<point>"],"risks":["<point>","<point>"],"recommendation":"<Buy / Pass / Negotiate>"}`;

    const res = await claudeAPICall([{ role: 'user', content: prompt }], systemPrompt, 0.7);
    if (res.ok) {
      try {
        const match = res.text.match(/\{[\s\S]*\}/);
        if (!match) throw new Error('No JSON found');
        setResult(JSON.parse(match[0]));
      } catch {
        setError('Could not parse AI response.');
      }
    } else {
      setError(res.error);
    }
    setLoading(false);
  };

  const scoreColor = result ? (result.score >= 7 ? '#16a34a' : result.score >= 5 ? '#d97706' : '#dc2626') : '#666';

  return (
    <div className="card" style={{ marginTop: 16 }}>
      <div className="card-head"><h3>AI Deal Score</h3></div>
      <div className="card-body">
        {!result && !loading && (
          <div>
            <p style={{ fontSize: 13, color: '#666', marginBottom: 12 }}>Let Claude AI analyze this rental deal and give it a score based on cash flow, cap rate, DSCR, and long-term return metrics.</p>
            <button onClick={score} style={{ padding: '8px 18px', background: '#000', color: '#fff', border: 'none', borderRadius: 5, cursor: 'pointer', fontWeight: 600 }}>
              Score This Deal with AI
            </button>
            {error && <div style={{ color: 'red', marginTop: 10, fontSize: 13 }}>⚠ {error}</div>}
          </div>
        )}
        {loading && <div style={{ color: '#666', fontSize: 14 }}>Analyzing deal... please wait.</div>}
        {result && (
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginBottom: 16 }}>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 52, fontWeight: 800, color: scoreColor, lineHeight: 1 }}>{result.score}</div>
                <div style={{ fontSize: 11, color: '#999', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.06em' }}>out of 10</div>
              </div>
              <div>
                <div style={{ fontSize: 18, fontWeight: 700, color: scoreColor }}>{result.verdict}</div>
                <div style={{ fontSize: 13, color: '#444', marginTop: 4 }}>{result.summary}</div>
                <div style={{ marginTop: 8 }}>
                  <span style={{ padding: '3px 10px', borderRadius: 20, fontSize: 12, fontWeight: 700, background: scoreColor, color: '#fff' }}>{result.recommendation}</span>
                </div>
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em', color: '#16a34a', marginBottom: 6 }}>Strengths</div>
                {(result.strengths || []).map((s, i) => <div key={i} style={{ fontSize: 13, marginBottom: 4 }}>✓ {s}</div>)}
              </div>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em', color: '#dc2626', marginBottom: 6 }}>Risks</div>
                {(result.risks || []).map((r, i) => <div key={i} style={{ fontSize: 13, marginBottom: 4 }}>⚠ {r}</div>)}
              </div>
            </div>
            <button onClick={score} style={{ marginTop: 14, padding: '6px 14px', background: '#f0f0f0', border: 'none', borderRadius: 4, cursor: 'pointer', fontSize: 12 }}>Re-analyze</button>
          </div>
        )}
      </div>
    </div>
  );
}

/* ============ Rental Property Investment Calculator ============ */

function RentalPropertyTab({ deal, calc, update }) {
  const t = deal.terms;
  const p = deal.property;
  const r = deal.rentalAnalysis || {
    monthlyRent: 0,
    vacancyRate: 5,
    propertyTaxMonthly: 0,
    insuranceMonthly: 0,
    maintenanceMonthly: 0,
    propertyManagementPct: 8,
    capexReserveMonthly: 0,
    holdinPeriod: 120, // 10 years
  };

  const setRental = (k, v) => update({ rentalAnalysis: { ...r, [k]: v } });

  const monthlyRent = r.monthlyRent || 0;
  const annualRent = monthlyRent * 12;
  const annualVacancyLoss = annualRent * (r.vacancyRate / 100);
  const effectiveGrossIncome = annualRent - annualVacancyLoss;

  const annualTax = (r.propertyTaxMonthly || 0) * 12;
  const annualInsurance = (r.insuranceMonthly || 0) * 12;
  const annualMaintenance = (r.maintenanceMonthly || 0) * 12;
  const mgmtPct = r.propertyManagementPct || 8;
  const annualMgmt = effectiveGrossIncome * (mgmtPct / 100);
  const annualCapex = (r.capexReserveMonthly || 0) * 12;

  const totalOperatingExpenses = annualTax + annualInsurance + annualMaintenance + annualMgmt + annualCapex;
  const noi = effectiveGrossIncome - totalOperatingExpenses;

  const purchasePrice = t.acceptedPrice || 0;
  const downPaymentAmt = calc.mort?.cashToClose || Math.round(purchasePrice * 0.2);
  const capRate = purchasePrice ? (noi / purchasePrice) * 100 : 0;
  const cashOnCash = downPaymentAmt ? (noi / downPaymentAmt) * 100 : 0;

  const annualDebtService = (calc.mort?.pay || 0) * 12;
  const dscr = noi / Math.max(1, annualDebtService); // Debt Service Coverage Ratio
  const cashFlow = noi - annualDebtService;
  const holdingMonths = r.holdingPeriod || 120;
  const holdingYears = holdingMonths / 12;
  const totalCashFlow = cashFlow * holdingYears;
  const appreciationRate = r.appreciationAnnual || 3;
  const futureValue = purchasePrice * Math.pow(1 + appreciationRate / 100, holdingYears);
  const appreciation = futureValue - purchasePrice;
  const totalReturn = totalCashFlow + appreciation;
  const roi = downPaymentAmt ? (totalReturn / downPaymentAmt) * 100 : 0;

  return (
    <div>
      <div className="deal-summary-row">
        <div className="deal-summary-card">
          <div className="deal-summary-label">Monthly Rent</div>
          <div className="deal-summary-value small">
            <MoneyInput value={monthlyRent} onChange={(v) => setRental('monthlyRent', v)} />
          </div>
        </div>
        <div className="deal-summary-card">
          <div className="deal-summary-label">Cap Rate</div>
          <div className="deal-summary-value small">{fmtPct(capRate)}</div>
        </div>
        <div className="deal-summary-card">
          <div className="deal-summary-label">Cash on Cash</div>
          <div className="deal-summary-value small">{fmtPct(cashOnCash)}</div>
        </div>
        <div className="deal-summary-card">
          <div className="deal-summary-label">Annual Cash Flow</div>
          <div className="deal-summary-value small">{fmtMoney(cashFlow)}</div>
        </div>
      </div>

      <div className="offer-guidance-box">
        <div className="offer-guidance-title">Rental Property Analysis</div>
        <div className="offer-guidance-copy">Calculate buy-and-hold returns including cap rate, cash-on-cash, and long-term appreciation.</div>
      </div>

      <div className="grid">
        <div className="col">
          <div className="card">
            <div className="card-head"><h3>Rental Income & Expenses</h3></div>
            <div className="card-body">
              <div className="frow"><div className="frow-label">Monthly Rent</div><div className="frow-right"><MoneyInput value={monthlyRent} onChange={(v) => setRental('monthlyRent', v)} /></div></div>
              <div className="frow"><div className="frow-label">Annual Rent</div><div className="in zero">{fmtMoney(annualRent)}</div></div>
              <div className="frow"><div className="frow-label">Vacancy Rate</div><div className="frow-right"><NumInput value={r.vacancyRate} onChange={(v) => setRental('vacancyRate', v || 0)} suffix="%" /></div></div>
              <div className="frow"><div className="frow-label">Vacancy Loss</div><div className="in zero">{fmtMoney(annualVacancyLoss)}</div></div>
              <div className="frow"><div className="frow-label">Effective Gross Income</div><div className="in zero">{fmtMoney(effectiveGrossIncome)}</div></div>
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h3>Operating Expenses</h3><span className="head-total">{fmtMoney(totalOperatingExpenses)}</span></div>
            <div className="card-body">
              <div className="frow"><div className="frow-label">Property Tax (monthly)</div><div className="frow-right"><MoneyInput value={r.propertyTaxMonthly} onChange={(v) => setRental('propertyTaxMonthly', v)} /></div></div>
              <div className="frow"><div className="frow-label">Annual Tax</div><div className="in zero">{fmtMoney(annualTax)}</div></div>
              <div className="frow"><div className="frow-label">Insurance (monthly)</div><div className="frow-right"><MoneyInput value={r.insuranceMonthly} onChange={(v) => setRental('insuranceMonthly', v)} /></div></div>
              <div className="frow"><div className="frow-label">Annual Insurance</div><div className="in zero">{fmtMoney(annualInsurance)}</div></div>
              <div className="frow"><div className="frow-label">Maintenance (monthly)</div><div className="frow-right"><MoneyInput value={r.maintenanceMonthly} onChange={(v) => setRental('maintenanceMonthly', v)} /></div></div>
              <div className="frow"><div className="frow-label">Annual Maintenance</div><div className="in zero">{fmtMoney(annualMaintenance)}</div></div>
              <div className="frow"><div className="frow-label">Mgmt Fee</div><div className="frow-right"><NumInput value={mgmtPct} onChange={(v) => setRental('propertyManagementPct', v || 0)} suffix="%" /></div></div>
              <div className="frow"><div className="frow-label">Annual Mgmt Cost</div><div className="in zero">{fmtMoney(annualMgmt)}</div></div>
              <div className="frow"><div className="frow-label">CapEx Reserve (monthly)</div><div className="frow-right"><MoneyInput value={r.capexReserveMonthly} onChange={(v) => setRental('capexReserveMonthly', v)} /></div></div>
              <div className="frow"><div className="frow-label">Annual CapEx</div><div className="in zero">{fmtMoney(annualCapex)}</div></div>
            </div>
          </div>
        </div>

        <div className="col">
          <div className="card">
            <div className="card-head"><h3>Profitability Metrics</h3></div>
            <div className="card-body">
              <div className="frow"><div className="frow-label">NOI (Net Operating Income)</div><div className="in zero">{fmtMoney(noi)}</div></div>
              <div className="frow"><div className="frow-label">Purchase Price</div><div className="in zero">{fmtMoney(purchasePrice)}</div></div>
              <div className="frow"><div className="frow-label">Cap Rate</div><div className="in zero" style={{ fontSize: 16, fontWeight: 700 }}>{fmtPct(capRate)}</div></div>
              <div className="frow"><div className="frow-label">Down Payment</div><div className="in zero">{fmtMoney(downPaymentAmt)}</div></div>
              <div className="frow"><div className="frow-label">Cash on Cash Return</div><div className="in zero" style={{ fontSize: 16, fontWeight: 700 }}>{fmtPct(cashOnCash)}</div></div>
              <div className="frow"><div className="frow-label">DSCR (Debt Service Coverage)</div><div className="in zero">{dscr.toFixed(2)}x</div></div>
              <div className="frow"><div className="frow-label">Annual Cash Flow</div><div className="in zero">{fmtMoney(cashFlow)}</div></div>
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h3>Hold & Appreciation</h3></div>
            <div className="card-body">
              <div className="frow"><div className="frow-label">Holding Period</div><div className="frow-right"><NumInput value={holdingMonths} onChange={(v) => setRental('holdingPeriod', v || 120)} suffix="months" /></div></div>
              <div className="frow"><div className="frow-label">Years</div><div className="in zero">{holdingYears.toFixed(1)}</div></div>
              <div className="frow"><div className="frow-label">Annual Appreciation</div><div className="frow-right"><NumInput value={r.appreciationAnnual || 3} onChange={(v) => setRental('appreciationAnnual', v || 3)} suffix="%" /></div></div>
              <div className="frow"><div className="frow-label">Future Value</div><div className="in zero">{fmtMoney(futureValue)}</div></div>
              <div className="frow"><div className="frow-label">Appreciation Gain</div><div className="in zero">{fmtMoney(appreciation)}</div></div>
              <div className="frow"><div className="frow-label">Total Cash Flow</div><div className="in zero">{fmtMoney(totalCashFlow)}</div></div>
              <div className="frow"><div className="frow-label">Total Return</div><div className="in zero" style={{ fontSize: 16, fontWeight: 700 }}>{fmtMoney(totalReturn)}</div></div>
              <div className="frow"><div className="frow-label">Hold Period ROI</div><div className="in zero" style={{ fontSize: 16, fontWeight: 700 }}>{fmtPct(roi)}</div></div>
            </div>
          </div>
        </div>

        <div className="col span-charts">
          <div className="card">
            <div className="card-head"><h3>5-Year Projection</h3></div>
            <div className="card-body">
              <table className="cmp-tbl" style={{ width: '100%' }}>
                <thead>
                  <tr><th>Year</th><th>Cash Flow</th><th>Cumulative</th><th>Property Value</th></tr>
                </thead>
                <tbody>
                  {Array.from({ length: Math.min(5, Math.ceil(holdingYears)) }, (_, i) => {
                    const yr = i + 1;
                    const cumCashFlow = cashFlow * yr;
                    const propVal = purchasePrice * Math.pow(1 + appreciationRate / 100, yr);
                    return (
                      <tr key={yr}>
                        <td>Yr {yr}</td>
                        <td>{fmtMoney(cashFlow)}</td>
                        <td>{fmtMoney(cumCashFlow)}</td>
                        <td>{fmtMoney(propVal)}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h3>Key Insights</h3></div>
            <div className="card-body" style={{ fontSize: 13.5, lineHeight: 1.7 }}>
              <div style={{ marginBottom: 12 }}>
                <strong>Cap Rate:</strong> {capRate >= 8 ? '✓ Strong' : capRate >= 5 ? 'Moderate' : '⚠ Below market'} ({fmtPct(capRate)})
              </div>
              <div style={{ marginBottom: 12 }}>
                <strong>Cash Flow:</strong> {cashFlow > 0 ? `✓ ${fmtMoney(cashFlow)}/year` : `⚠ Negative`}
              </div>
              <div style={{ marginBottom: 12 }}>
                <strong>DSCR:</strong> {dscr >= 1.25 ? '✓ Lender approved' : dscr >= 1.0 ? 'Acceptable' : '⚠ Below 1.0 (won\'t qualify)'}
              </div>
              <div>
                <strong>Long-term Return:</strong> {totalReturn > 0 ? `✓ ${fmtMoney(totalReturn)} over ${holdingYears.toFixed(1)} years` : 'Negative'}
              </div>
            </div>
          </div>
        </div>
      </div>

      <RentalAIScore deal={deal} rentalMetrics={{
        purchasePrice, monthlyRent, noi, capRate, cashOnCash, dscr, cashFlow,
        vacancyRate: r.vacancyRate, holdingYears, totalReturn, roi,
      }} />
    </div>
  );
}

Object.assign(window, { RentalPropertyTab, RentalAIScore });
