// Rates & Tools page — affordability calc, refi savings, rate table
const { useState: useStateR, useMemo: useMemoR } = React;

function Affordability() {
  const [income, setIncome] = useStateR(180000);
  const [debt, setDebt] = useStateR(650);
  const [down, setDown] = useStateR(80000);
  const [rate, setRate] = useStateR(6.390);
  const [dti, setDti] = useStateR(43);

  const r = useMemoR(() => {
    const monthlyIncome = income / 12;
    const maxPITI = (monthlyIncome * (dti / 100)) - debt;
    const i = rate / 100 / 12;
    const n = 360;
    const taxIns = 0.0125; // 1.25% annual of price
    // approximate: solve for price s.t. PI(price-down) + price*taxIns/12 = maxPITI
    // PI = (price - down) * factor; factor = (i*(1+i)^n)/((1+i)^n - 1)
    const factor = (i * Math.pow(1 + i, n)) / (Math.pow(1 + i, n) - 1);
    const price = (maxPITI + down * factor) / (factor + taxIns / 12);
    const principal = Math.max(0, price - down);
    const pi = principal * factor;
    const ti = price * taxIns / 12;
    return { price: Math.max(0, price), pi, ti, total: pi + ti, maxPITI };
  }, [income, debt, down, rate, dti]);

  return (
    <div className="calc-wrap" id="affordability">
      <div className="calc-form">
        <h3>How much home can you afford?</h3>
        <div className="field">
          <label>Annual household income <span className="v">{fmtUSD(income)}</span></label>
          <input type="range" min="40000" max="600000" step="5000" value={income} onChange={e => setIncome(+e.target.value)} />
        </div>
        <div className="field">
          <label>Monthly debt payments <span className="v">{fmtUSD(debt)}</span></label>
          <input type="range" min="0" max="5000" step="50" value={debt} onChange={e => setDebt(+e.target.value)} />
        </div>
        <div className="field">
          <label>Available down payment <span className="v">{fmtUSD(down)}</span></label>
          <input type="range" min="0" max="500000" step="2500" value={down} onChange={e => setDown(+e.target.value)} />
        </div>
        <div className="field">
          <label>Interest rate <span className="v">{rate.toFixed(3)}%</span></label>
          <input type="range" min="3" max="9" step="0.125" value={rate} onChange={e => setRate(+e.target.value)} />
        </div>
        <div className="field">
          <label>Debt-to-income ceiling <span className="v">{dti}%</span></label>
          <input type="range" min="28" max="50" step="1" value={dti} onChange={e => setDti(+e.target.value)} />
        </div>
      </div>
      <div className="calc-out">
        <div className="label">Maximum home price</div>
        <div className="big">{fmtUSD(r.price)}</div>
        <div className="sub">Based on a {dti}% DTI ceiling and a 30-year fixed at {rate.toFixed(3)}%</div>
        <div className="calc-breakdown" style={{marginTop:24}}>
          <dl>
            <dt>Maximum monthly PITI</dt><dd>{fmtUSD(r.maxPITI, 0)}</dd>
            <dt>Estimated principal & interest</dt><dd>{fmtUSD(r.pi, 0)}</dd>
            <dt>Estimated taxes & insurance</dt><dd>{fmtUSD(r.ti, 0)}</dd>
            <dt>Down payment</dt><dd>{fmtUSD(down, 0)}</dd>
          </dl>
        </div>
      </div>
    </div>
  );
}

function RefiSavings() {
  const [balance, setBalance] = useStateR(420000);
  const [oldRate, setOldRate] = useStateR(7.250);
  const [newRate, setNewRate] = useStateR(6.390);
  const [term, setTerm] = useStateR(30);

  const r = useMemoR(() => {
    const calc = (rate) => {
      const i = rate / 100 / 12;
      const n = term * 12;
      return balance * (i * Math.pow(1 + i, n)) / (Math.pow(1 + i, n) - 1);
    };
    const oldPI = calc(oldRate);
    const newPI = calc(newRate);
    const monthlySavings = oldPI - newPI;
    const fiveYr = monthlySavings * 60;
    const lifetime = monthlySavings * term * 12;
    return { oldPI, newPI, monthlySavings, fiveYr, lifetime };
  }, [balance, oldRate, newRate, term]);

  return (
    <div className="calc-wrap" id="refi">
      <div className="calc-form">
        <h3>Refinance savings</h3>
        <div className="field">
          <label>Current loan balance <span className="v">{fmtUSD(balance)}</span></label>
          <input type="range" min="50000" max="2000000" step="5000" value={balance} onChange={e => setBalance(+e.target.value)} />
        </div>
        <div className="field">
          <label>Current rate <span className="v">{oldRate.toFixed(3)}%</span></label>
          <input type="range" min="3" max="10" step="0.125" value={oldRate} onChange={e => setOldRate(+e.target.value)} />
        </div>
        <div className="field">
          <label>New rate <span className="v">{newRate.toFixed(3)}%</span></label>
          <input type="range" min="3" max="10" step="0.125" value={newRate} onChange={e => setNewRate(+e.target.value)} />
        </div>
        <div className="field">
          <label>New term</label>
          <div className="field-pills">
            {[10,15,20,30].map(t => <button key={t} className={term===t?"active":""} onClick={()=>setTerm(t)}>{t}-year</button>)}
          </div>
        </div>
      </div>
      <div className="calc-out">
        <div className="label">Estimated monthly savings</div>
        <div className="big" style={{color: r.monthlySavings >= 0 ? "var(--ink)" : "var(--red)"}}>{fmtUSD(r.monthlySavings, 0)}</div>
        <div className="sub">{r.monthlySavings >= 0 ? "You'd save" : "You'd add"} {fmtUSD(Math.abs(r.monthlySavings),0)} per month</div>
        <div className="calc-breakdown" style={{marginTop:24}}>
          <dl>
            <dt>Current monthly P&I</dt><dd>{fmtUSD(r.oldPI, 0)}</dd>
            <dt>New monthly P&I</dt><dd>{fmtUSD(r.newPI, 0)}</dd>
            <dt>5-year savings</dt><dd>{fmtUSD(r.fiveYr, 0)}</dd>
            <dt>Lifetime savings</dt><dd>{fmtUSD(r.lifetime, 0)}</dd>
          </dl>
        </div>
      </div>
    </div>
  );
}

function RatesPage() {
  const rates = [
    { product: "30-Year Fixed",      rate: 6.390, apr: 6.478, points: 0.000, pi: "$2,499" },
    { product: "30-Year Fixed (1pt)",rate: 6.125, apr: 6.275, points: 1.000, pi: "$2,432" },
    { product: "20-Year Fixed",      rate: 6.125, apr: 6.214, points: 0.000, pi: "$2,902" },
    { product: "15-Year Fixed",      rate: 5.730, apr: 5.842, points: 0.000, pi: "$3,318" },
    { product: "10-Year Fixed",      rate: 5.500, apr: 5.648, points: 0.000, pi: "$4,346" },
    { product: "7/6 ARM",            rate: 5.875, apr: 6.378, points: 0.000, pi: "$2,367" },
    { product: "5/6 ARM",            rate: 5.750, apr: 6.342, points: 0.000, pi: "$2,335" },
    { product: "FHA 30-Year",        rate: 6.150, apr: 6.685, points: 0.000, pi: "$2,438" },
    { product: "VA 30-Year",         rate: 6.020, apr: 6.082, points: 0.000, pi: "$2,405" },
    { product: "USDA 30-Year",       rate: 6.250, apr: 6.345, points: 0.000, pi: "$2,464" },
    { product: "Jumbo 30-Year",      rate: 6.432, apr: 6.481, points: 0.000, pi: "$2,510" },
    { product: "DSCR Investor",      rate: 7.375, apr: 7.642, points: 0.000, pi: "$2,762" },
  ];

  return (
    <>
      <UtilityBar />
      <Header active="rates" />
      <Crumb items={[{ label: "Home", href: "index.html" }, { label: "Rates & Tools" }]} />

      <section className="page-hero">
        <div className="container">
          <div className="section-num">Rates & Tools</div>
          <h1>Today's rates. Real calculators. No fine-print surprises.</h1>
          <p className="lede">Sample rates updated daily by 9:30 AM ET. The calculators below use the same amortization engine our underwriters use — what you see is what we'll quote.</p>
        </div>
      </section>

      <Ticker />

      <section className="section">
        <div className="container">
          <div className="section-num" style={{marginBottom:16}}>Rate sheet · Updated 9:34 AM ET</div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Product</th>
                <th className="num">Rate</th>
                <th className="num">APR</th>
                <th className="num">Points</th>
                <th className="num">Sample P&I*</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {rates.map(r => (
                <tr key={r.product}>
                  <td><strong>{r.product}</strong></td>
                  <td className="num">{r.rate.toFixed(3)}%</td>
                  <td className="num">{r.apr.toFixed(3)}%</td>
                  <td className="num">{r.points.toFixed(3)}</td>
                  <td className="num">{r.pi}</td>
                  <td className="num"><a href="apply.html" style={{color:"var(--navy)",fontWeight:500}}>Lock →</a></td>
                </tr>
              ))}
            </tbody>
          </table>
          <p style={{fontSize:12,color:"var(--ink-4)",marginTop:16,maxWidth:"80ch",lineHeight:1.6}}>
            *Assumes $400,000 loan amount, 740 FICO, owner-occupied single-family residence, 30-day rate lock, 20% down (where applicable). APR includes estimated closing costs. Rates are illustrative and subject to change. Your actual rate depends on credit profile, loan-to-value, occupancy, and product. NMLS #1184872.
          </p>
        </div>
      </section>

      <section className="section alt">
        <div className="container">
          <div className="section-num" style={{marginBottom:16}}>Affordability calculator</div>
          <Affordability />
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div className="section-num" style={{marginBottom:16}}>Refinance savings</div>
          <RefiSavings />
        </div>
      </section>

      <section className="section alt">
        <div className="container">
          <div className="section-num" style={{marginBottom:16}}>Full payment calculator</div>
          <MortgageCalc />
        </div>
      </section>

      <Footer />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<RatesPage />);
