// Larkspur — Borrowing Power Calculator (full)

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "navy"
}/*EDITMODE-END*/;

const ACCENT_PALETTES = {
  navy:    { brand: '#1a3a8f', deep: '#0f1f4a', soft: '#e7ebf6' },
  forest:  { brand: '#0d3b2e', deep: '#072018', soft: '#dce8e2' },
  bronze:  { brand: '#7a4a1a', deep: '#42260c', soft: '#efe4d4' },
  ink:     { brand: '#1a1a1a', deep: '#000000', soft: '#e8e8e8' },
  plum:    { brand: '#4a1a4a', deep: '#2a0d2a', soft: '#ece0ec' },
};

const fmt = (n) => '$' + Math.round(n).toLocaleString('en-AU');
const fmtK = (n) => n >= 1000000 ? '$' + (n/1000000).toFixed(2) + 'M' : '$' + Math.round(n/1000).toLocaleString('en-AU') + 'k';

const CalcApp = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [bookOpen, setBookOpen] = React.useState(false);

  // Inputs
  const [applicants, setApplicants] = React.useState('joint'); // single | joint
  const [income1, setIncome1] = React.useState(120000);
  const [income2, setIncome2] = React.useState(95000);
  const [otherIncome, setOtherIncome] = React.useState(0);
  const [deposit, setDeposit] = React.useState(180000);
  const [dependants, setDependants] = React.useState(2);
  const [livingExp, setLivingExp] = React.useState(4200);
  const [creditLimit, setCreditLimit] = React.useState(15000);
  const [otherDebt, setOtherDebt] = React.useState(0);
  const [purpose, setPurpose] = React.useState('owner'); // owner | investment
  const [term, setTerm] = React.useState(30);
  const [rate, setRate] = React.useState(6.24);

  React.useEffect(() => {
    const p = ACCENT_PALETTES[tweaks.accent] || ACCENT_PALETTES.navy;
    document.documentElement.style.setProperty('--brand', p.brand);
    document.documentElement.style.setProperty('--brand-deep', p.deep);
    document.documentElement.style.setProperty('--brand-soft', p.soft);
  }, [tweaks.accent]);

  // Indicative servicing calc
  const grossIncome = applicants === 'joint' ? income1 + income2 + otherIncome : income1 + otherIncome;
  // crude tax (effective)
  const taxRate = grossIncome > 180000 ? 0.32 : grossIncome > 120000 ? 0.28 : grossIncome > 45000 ? 0.22 : 0.16;
  const netMonthly = (grossIncome * (1 - taxRate)) / 12;
  const dependantCost = dependants * 650;
  const creditServ = creditLimit * 0.038; // 3.8% of credit limit treated as monthly
  const otherDebtServ = otherDebt;
  const buffer = 0.03; // assessment rate buffer
  const assessRate = (rate + 3) / 100;
  const monthlyAvail = Math.max(0, netMonthly - livingExp - dependantCost - creditServ - otherDebtServ);
  const investorBoost = purpose === 'investment' ? 1.08 : 1.0;
  // Borrowing capacity from monthly available, term n, monthly rate i
  const i = assessRate / 12;
  const n = term * 12;
  const principal = monthlyAvail > 0 ? (monthlyAvail * (1 - Math.pow(1 + i, -n)) / i) * investorBoost : 0;
  const borrow = Math.max(0, Math.min(principal, grossIncome * 8));
  const propertyValue = borrow + deposit;

  // Range bar position
  const lo = 200000, hi = 3000000;
  const pct = Math.min(100, Math.max(0, ((borrow - lo) / (hi - lo)) * 100));

  // Repayment at actual rate
  const ri = rate / 100 / 12;
  const repayMonthly = borrow > 0 ? (borrow * ri) / (1 - Math.pow(1 + ri, -n)) : 0;

  return (
    <>
      <Header active="calc" onBook={() => setBookOpen(true)} />
      <main>
        <section className="calc-page-hero" data-screen-label="01 Calculator hero">
          <div className="container">
            <div className="breadcrumb">
              <a href="index.html">Home</a>
              <span className="sep">/</span>
              <a href="#">Calculators</a>
              <span className="sep">/</span>
              <span className="current">Borrowing power</span>
            </div>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'end', gap:32, flexWrap:'wrap', marginTop:8}}>
              <div style={{maxWidth:680}}>
                <span className="eyebrow">Calculator · Borrowing power</span>
                <h1 style={{marginTop:24, fontSize:'clamp(36px, 4.4vw, 60px)'}}>How much could you <span style={{color:'var(--brand)'}}>borrow</span>?</h1>
                <p className="lead muted" style={{marginTop:20, maxWidth:560}}>An indicative estimate using a typical lender servicing model. For a real assessment across 35+ lenders, book a 30-min strategy review.</p>
              </div>
              <button className="btn btn-primary btn-lg" onClick={() => setBookOpen(true)}>
                Get a real assessment
                <span className="arrow"><Icon name="arrow-right" size={14}/></span>
              </button>
            </div>
          </div>
        </section>

        <section style={{padding:'24px 0 96px'}} data-screen-label="02 Calculator">
          <div className="container">
            <div className="calc-layout">
              <div className="calc-form">
                <div className="section-label">Applicants</div>
                <div className="toggle-row" style={{marginBottom:16}}>
                  <button className={applicants==='single'?'active':''} onClick={()=>setApplicants('single')}>Single</button>
                  <button className={applicants==='joint'?'active':''} onClick={()=>setApplicants('joint')}>Joint</button>
                </div>

                <div className="field" style={{marginTop:0}}>
                  <div style={{display:'flex', justifyContent:'space-between'}}>
                    <label>Applicant 1 income</label>
                    <span style={{fontSize:13, color:'var(--muted)'}}>{fmt(income1)}/yr</span>
                  </div>
                  <input type="range" min="40000" max="500000" step="5000" value={income1} onChange={e=>setIncome1(+e.target.value)}/>
                </div>
                {applicants === 'joint' && (
                  <div className="field">
                    <div style={{display:'flex', justifyContent:'space-between'}}>
                      <label>Applicant 2 income</label>
                      <span style={{fontSize:13, color:'var(--muted)'}}>{fmt(income2)}/yr</span>
                    </div>
                    <input type="range" min="0" max="500000" step="5000" value={income2} onChange={e=>setIncome2(+e.target.value)}/>
                  </div>
                )}
                <div className="field">
                  <div style={{display:'flex', justifyContent:'space-between'}}>
                    <label>Other income (rent, bonus, etc.)</label>
                    <span style={{fontSize:13, color:'var(--muted)'}}>{fmt(otherIncome)}/yr</span>
                  </div>
                  <input type="range" min="0" max="200000" step="2500" value={otherIncome} onChange={e=>setOtherIncome(+e.target.value)}/>
                </div>

                <div className="section-label">Deposit &amp; loan</div>
                <div className="field" style={{marginTop:0}}>
                  <label>Deposit</label>
                  <div className="input-with-prefix">
                    <span className="prefix">$</span>
                    <input type="number" value={deposit} onChange={e=>setDeposit(+e.target.value || 0)}/>
                  </div>
                </div>
                <div className="field-pair" style={{marginTop:12}}>
                  <div className="field" style={{marginTop:0}}>
                    <label>Loan term</label>
                    <div className="input-with-prefix">
                      <input type="number" value={term} onChange={e=>setTerm(+e.target.value||30)}/>
                      <span className="prefix" style={{marginLeft:6, marginRight:0}}>yrs</span>
                    </div>
                  </div>
                  <div className="field" style={{marginTop:0}}>
                    <label>Interest rate</label>
                    <div className="input-with-prefix">
                      <input type="number" step="0.01" value={rate} onChange={e=>setRate(+e.target.value||6)}/>
                      <span className="prefix" style={{marginLeft:6, marginRight:0}}>%</span>
                    </div>
                  </div>
                </div>
                <div className="section-label">Purpose</div>
                <div className="toggle-row">
                  <button className={purpose==='owner'?'active':''} onClick={()=>setPurpose('owner')}>Owner-occupied</button>
                  <button className={purpose==='investment'?'active':''} onClick={()=>setPurpose('investment')}>Investment</button>
                </div>

                <div className="section-label">Expenses &amp; commitments</div>
                <div className="field" style={{marginTop:0}}>
                  <div style={{display:'flex', justifyContent:'space-between'}}>
                    <label>Dependants</label>
                    <span style={{fontSize:13, color:'var(--muted)'}}>{dependants}</span>
                  </div>
                  <input type="range" min="0" max="6" step="1" value={dependants} onChange={e=>setDependants(+e.target.value)}/>
                </div>
                <div className="field">
                  <div style={{display:'flex', justifyContent:'space-between'}}>
                    <label>Monthly living expenses</label>
                    <span style={{fontSize:13, color:'var(--muted)'}}>{fmt(livingExp)}/mo</span>
                  </div>
                  <input type="range" min="2000" max="12000" step="100" value={livingExp} onChange={e=>setLivingExp(+e.target.value)}/>
                </div>
                <div className="field">
                  <label>Total credit card limits</label>
                  <div className="input-with-prefix">
                    <span className="prefix">$</span>
                    <input type="number" value={creditLimit} onChange={e=>setCreditLimit(+e.target.value||0)}/>
                  </div>
                </div>
                <div className="field">
                  <label>Other monthly loan repayments</label>
                  <div className="input-with-prefix">
                    <span className="prefix">$</span>
                    <input type="number" value={otherDebt} onChange={e=>setOtherDebt(+e.target.value||0)}/>
                  </div>
                </div>
              </div>

              <div className="calc-results">
                <div className="result-card">
                  <div className="label-top">Indicative borrowing capacity</div>
                  <div className="big-num">{fmtK(borrow)}</div>
                  <div className="sub">Including your {fmt(deposit)} deposit, that's a property up to <strong style={{color:'#fff'}}>{fmtK(propertyValue)}</strong>.</div>
                  <div className="range-bar">
                    <div className="range-fill" style={{left:0, width:`${pct}%`}}/>
                  </div>
                  <div className="range-meta">
                    <span>{fmtK(lo)}</span>
                    <span>{fmtK(hi)}+</span>
                  </div>
                </div>

                <div className="scenario-grid">
                  <div className="scenario">
                    <div className="name">Estimated monthly repayment</div>
                    <div className="amt">{fmt(repayMonthly)}</div>
                    <div className="delta">at {rate.toFixed(2)}% over {term}yrs</div>
                  </div>
                  <div className="scenario">
                    <div className="name">Loan-to-value (LVR)</div>
                    <div className="amt">{propertyValue > 0 ? Math.round((borrow/propertyValue)*100) : 0}%</div>
                    <div className="delta">{borrow/propertyValue > 0.8 ? 'LMI likely applies' : 'No LMI required'}</div>
                  </div>
                  <div className="scenario">
                    <div className="name">Stamp duty (NSW est.)</div>
                    <div className="amt">{fmt(propertyValue * 0.04)}</div>
                    <div className="delta">approx — varies by state</div>
                  </div>
                </div>

                <div style={{background:'var(--surface)', border:'1px solid var(--line-soft)', borderRadius:'var(--radius-lg)', padding:32}}>
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'start', gap:16, flexWrap:'wrap'}}>
                    <div>
                      <h3 style={{fontSize:22, fontWeight:500}}>Want a real number across 35+ lenders?</h3>
                      <p className="muted" style={{marginTop:8, maxWidth:480, fontSize:14.5}}>This calculator uses a generic servicing model. Different lenders assess income, expenses and add-backs differently — gaps of $200k+ are normal.</p>
                    </div>
                    <button className="btn btn-primary" onClick={()=>setBookOpen(true)}>
                      Book a lending review
                      <span className="arrow"><Icon name="arrow-right" size={12}/></span>
                    </button>
                  </div>
                  <div style={{marginTop:24, paddingTop:24, borderTop:'1px solid var(--line-soft)', display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:16}}>
                    <div style={{display:'flex', gap:12}}>
                      <span style={{width:32, height:32, borderRadius:'50%', background:'var(--brand-soft)', color:'var(--brand)', display:'inline-flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
                        <Icon name="check" size={14}/>
                      </span>
                      <div>
                        <div style={{fontSize:13.5, fontWeight:500}}>Multi-lender quote</div>
                        <div style={{fontSize:12.5, color:'var(--muted)', marginTop:2}}>Real numbers, not generic</div>
                      </div>
                    </div>
                    <div style={{display:'flex', gap:12}}>
                      <span style={{width:32, height:32, borderRadius:'50%', background:'var(--brand-soft)', color:'var(--brand)', display:'inline-flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
                        <Icon name="check" size={14}/>
                      </span>
                      <div>
                        <div style={{fontSize:13.5, fontWeight:500}}>Structure review</div>
                        <div style={{fontSize:12.5, color:'var(--muted)', marginTop:2}}>For your next 10 years</div>
                      </div>
                    </div>
                    <div style={{display:'flex', gap:12}}>
                      <span style={{width:32, height:32, borderRadius:'50%', background:'var(--brand-soft)', color:'var(--brand)', display:'inline-flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
                        <Icon name="check" size={14}/>
                      </span>
                      <div>
                        <div style={{fontSize:13.5, fontWeight:500}}>No obligation</div>
                        <div style={{fontSize:12.5, color:'var(--muted)', marginTop:2}}>30 minutes, free</div>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="disclaimer">
                  <strong style={{color:'var(--ink)'}}>Important:</strong> This calculator provides an indicative estimate only. It does not constitute credit assistance, a quote, or a pre-approval. Borrowing capacity varies materially across lenders. Talk to a Larkspur credit adviser for a formal assessment. Larkspur Lending Pty Ltd · ACL 000000.
                </div>
              </div>
            </div>
          </div>
        </section>

        <section style={{background:'var(--surface)', borderTop:'1px solid var(--line-soft)'}} data-screen-label="03 Other calculators">
          <div className="container">
            <div className="section-head">
              <div>
                <span className="eyebrow">More tools</span>
                <h2 style={{marginTop:16}}>Other calculators in this journey.</h2>
              </div>
            </div>
            <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:12}}>
              {[
                { i:'calc', t:'Loan comparison', d:'Compare two loans side by side over the full term.' },
                { i:'dollar', t:'Repayments', d:'P&I or interest-only — at any rate, term and balance.' },
                { i:'home', t:'Rent vs buy', d:'5-year and 10-year break-even modelling.' },
                { i:'spark', t:'Offset modelling', d:'See exactly how much an offset saves you.' },
              ].map((c, i) => (
                <div key={i} style={{background:'var(--bg)', border:'1px solid var(--line-soft)', borderRadius:'var(--radius)', padding:24}}>
                  <div style={{width:40, height:40, borderRadius:10, background:'var(--brand-soft)', color:'var(--brand)', display:'inline-flex', alignItems:'center', justifyContent:'center'}}>
                    <Icon name={c.i} size={20}/>
                  </div>
                  <h4 style={{marginTop:20, fontSize:17}}>{c.t}</h4>
                  <p style={{marginTop:6, fontSize:13.5, color:'var(--muted)'}}>{c.d}</p>
                  <div style={{marginTop:20, fontSize:13, color:'var(--brand)', fontWeight:500, display:'inline-flex', alignItems:'center', gap:8}}>
                    Open calculator <Icon name="arrow-right" size={12}/>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>
      </main>
      <Footer />
      <StickyCTA onClick={() => setBookOpen(true)} />
      <BookingModal open={bookOpen} onClose={() => setBookOpen(false)} context="lending" />

      <TweaksPanel title="Tweaks">
        <TweakSection title="Brand accent">
          <TweakRadio
            value={tweaks.accent}
            onChange={(v) => setTweak('accent', v)}
            options={[
              { value: 'navy', label: 'Navy' },
              { value: 'forest', label: 'Forest' },
              { value: 'bronze', label: 'Bronze' },
              { value: 'ink', label: 'Ink' },
              { value: 'plum', label: 'Plum' },
            ]}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<CalcApp />);
