/* ============ Shared schedule table ============ */
function ScheduleTable({ rows, yearly, interestOnly }) {
  const [view, setView] = React.useState(rows.length > 18 ? 'yearly' : 'monthly');
  const data = view === 'yearly' ? yearly : rows;
  const unit = view === 'yearly' ? 'Year' : 'Month';
  return (
    <div>
      <div className="sched-head">
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--green-900)' }}>
          Payment Schedule
        </div>
        {yearly && yearly.length > 1 ? (
          <div className="seg">
            <button className={view === 'monthly' ? 'on' : ''} onClick={() => setView('monthly')}>Monthly</button>
            <button className={view === 'yearly' ? 'on' : ''} onClick={() => setView('yearly')}>Yearly</button>
          </div>
        ) : null}
      </div>
      <div className="sched-scroll">
        <table className="sched">
          <thead>
            <tr>
              <th>{unit}</th>
              <th>Payment</th>
              <th>Interest</th>
              <th>{interestOnly ? 'Principal' : 'Principal'}</th>
              <th>Balance</th>
            </tr>
          </thead>
          <tbody>
            {data.map((row, i) => (
              <tr key={i}>
                <td>{view === 'yearly' ? row.year : row.m}</td>
                <td>{fmtMoney(row.pay, 0)}</td>
                <td>{fmtMoney(row.interest, 0)}</td>
                <td>{fmtMoney(row.princ, 0)}</td>
                <td>{fmtMoney(row.bal, 0)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function TermSheet({ cells }) {
  return (
    <div className="term-sheet">
      {cells.map((c, i) => (
        <div className="term-cell" key={i}><div className="l">{c.l}</div><div className="v" style={c.color ? { color: c.color } : null}>{c.v}</div></div>
      ))}
    </div>
  );
}

/* Linked input row — auto-syncs from Summary unless unlinked */
function LinkedRow({ label, sub, linked, value, onChange, onToggle }) {
  return (
    <div className="fs-row">
      <label>{label}{sub ? <small>{sub}</small> : null}</label>
      <div className="linked-wrap">
        <button className={'link-btn' + (linked ? ' on' : '')} onClick={onToggle}
          title={linked ? 'Synced from Summary — click to enter a custom value' : 'Custom value — click to re-sync from Summary'}>
          {linked ? (
            <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>
          ) : (
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 17H7A5 5 0 0 1 7 7h2M15 7h2a5 5 0 0 1 0 10h-2M8 12h8" /><path d="M2 2l20 20" /></svg>
          )}
        </button>
        <MoneyInput value={value} onChange={onChange} />
      </div>
    </div>
  );
}

/* ============ Mortgage Calculator ============ */
function MortgageCalc({ deal, calc, update }) {
  const m = deal.mortgage;
  const links = deal.links || {};
  const loanAmt = mortgageLoanAmount(deal);
  const set = (k, v) => update({ mortgage: { ...m, [k]: v } });
  const setLoan = (v) => update({ links: { ...links, mortgageLoan: false }, mortgage: { ...m, loanAmount: v } });
  const toggleLoan = () => update({ links: { ...links, mortgageLoan: !links.mortgageLoan } });
  const r = computeMortgage({ ...m, loanAmount: loanAmt });
  const sched = amortize(r.principal, m.rate, m.termYears);
  const yearly = groupByYear(sched.rows);
  const holdMonths = deal.terms.holdingMonths;
  const holdInterest = sched.rows.slice(0, holdMonths).reduce((a, x) => a + x.interest, 0);
  const cashInvested = loanAmt * m.downPct / 100 + calc.purchaseFeesSum + calc.rehabTotal;
  const coc = cashInvested ? (calc.netProfit / cashInvested) * 100 : 0;

  return (
    <div>
      <div className="fin-wrap">
        <div className="card">
          <div className="card-head"><h3>Loan Inputs</h3></div>
          <div className="card-body">
            <div className="field-stack">
              <LinkedRow label="Loan Amount" sub={links.mortgageLoan ? 'Synced to accepted price' : 'Custom amount'} linked={links.mortgageLoan} value={loanAmt} onChange={setLoan} onToggle={toggleLoan} />
              <div className="fs-row"><label>Down Payment</label><NumInput value={m.downPct} onChange={(v) => set('downPct', v || 0)} suffix="%" /></div>
              <div className="fs-row"><label>Interest Rate</label><NumInput value={m.rate} onChange={(v) => set('rate', v || 0)} suffix="% APR" /></div>
              <div className="fs-row"><label>Loan Term</label><NumInput value={m.termYears} onChange={(v) => set('termYears', v || 0)} suffix="years" /></div>
            </div>
            <p className="amort-note">Loan amount auto-syncs with the accepted price on the Summary tab. The monthly payment feeds the holding cost — multiplied by the holding period to estimate carry during the flip.</p>
          </div>
        </div>

        <div>
          <div className="fin-result">
            <div className="big-lbl">Monthly Payment</div>
            <div className="big-num">{fmtMoney(r.pay)}</div>
            <div className="fin-breakdown">
              <div className="fb"><span className="fl">Financed principal</span><span className="fv">{fmtMoney(r.principal)}</span></div>
              <div className="fb"><span className="fl">Down payment ({m.downPct}%)</span><span className="fv">{fmtMoney(loanAmt * m.downPct / 100)}</span></div>
              <div className="fb"><span className="fl">Total interest ({m.termYears} yr)</span><span className="fv">{fmtMoney(r.interest)}</span></div>
              <div className="fb total"><span className="fl">Total of payments</span><span className="fv">{fmtMoney(r.total)}</span></div>
            </div>
          </div>
          <div className="kpi-strip" style={{ gridTemplateColumns: '1fr 1fr 1fr' }}>
            <div className="kpi accent"><div className="l">Carry / Month</div><div className="v">{fmtMoney(r.pay)}</div><div className="hint">Principal + interest</div></div>
            <div className="kpi"><div className="l">Holding ({deal.terms.holdingMonths} mo)</div><div className="v">{fmtMoney(r.pay * deal.terms.holdingMonths)}</div><div className="hint">Applied to profit</div></div>
            <div className="kpi"><div className="l">Yearly Carry</div><div className="v">{fmtMoney(r.pay * 12)}</div><div className="hint">If held 12 months</div></div>
          </div>
          <div className="kpi-strip" style={{ gridTemplateColumns: '1fr 1fr 1fr', marginTop: 14 }}>
            <div className="kpi"><div className="l">Hold-Period Interest</div><div className="v">{fmtMoney(holdInterest)}</div><div className="hint">Interest over {holdMonths} mo</div></div>
            <div className="kpi"><div className="l">Cash Invested</div><div className="v">{fmtMoney(cashInvested)}</div><div className="hint">Down + fees + rehab</div></div>
            <div className="kpi accent"><div className="l">Cash-on-Cash</div><div className={'v' + (coc < 0 ? ' neg' : '')}>{fmtPct(coc)}</div><div className="hint">Flip profit ÷ cash in</div></div>
          </div>
        </div>
      </div>

      <div className="card" style={{ marginTop: 16 }}>
        <div className="card-head"><h3>Term Sheet &amp; Amortization</h3></div>
        <div className="card-body">
          <TermSheet cells={[
            { l: 'Monthly Payment', v: fmtMoney(r.pay) },
            { l: 'Principal Financed', v: fmtMoney(r.principal) },
            { l: 'Total Interest', v: fmtMoney(r.interest), color: 'var(--coral)' },
            { l: 'Payoff', v: m.termYears + ' yr · ' + (m.termYears * 12) + ' pmts' },
          ]} />
          <ScheduleTable rows={sched.rows} yearly={yearly} />
        </div>
      </div>
    </div>
  );
}

/* ============ Hard Money Calculator ============ */
function HardMoneyCalc({ deal, calc, update }) {
  const h = deal.hardMoney;
  const links = deal.links || {};
  const hi = hmInputs(deal, calc);
  const setH = (k, v) => update({ hardMoney: { ...h, [k]: v } });
  const setLinked = (flag, key, v) => update({ links: { ...links, [flag]: false }, hardMoney: { ...h, [key]: v } });
  const toggle = (flag) => update({ links: { ...links, [flag]: !links[flag] } });
  const loanMethod = h.loanMethod || 'ltc';
  const r = computeHardMoney({ ...h, purchasePrice: hi.purchasePrice, rehab: hi.rehab, arv: hi.arv, loanMethod });
  const sched = interestOnlySchedule(r.loan, h.rate, h.termMonths);
  const ex = deal.hardMoneyExtra || { originationPct: 1, processingFee: 995, draws: 3 };
  const setEx = (k, v) => update({ hardMoneyExtra: { ...ex, [k]: v } });
  const originationCost = r.loan * (ex.originationPct / 100);
  const upfront = r.pointsCost + originationCost + (ex.processingFee || 0);
  const trueCost = upfront + r.totalInterest;
  const drawCount = Math.max(1, Math.round(ex.draws || 1));
  const drawAmt = hi.rehab / drawCount;
  const drawRows = Array.from({ length: drawCount }, (_, i) => ({
    n: i + 1,
    month: Math.round(((i + 1) / drawCount) * Math.max(1, h.termMonths - 1)),
    amount: drawAmt,
    cumulative: drawAmt * (i + 1),
  }));

  const loanLabel = loanMethod === 'downpayment'
    ? 'Loan Amount (Purchase + Rehab − Down Payment)'
    : 'Loan Amount (Lesser of LTC & ARV caps)';

  return (
    <div>
      <div className="fin-wrap">
        <div className="card">
          <div className="card-head"><h3>Hard Money Inputs</h3></div>
          <div className="card-body">
            <div className="field-stack">
              {/* Loan method selector */}
              <div className="fs-row">
                <label>Loan Calculation Method</label>
                <div style={{ display: 'flex', gap: 8 }}>
                  {[['ltc', 'LTC / ARV Cap'], ['downpayment', 'Down Payment']].map(([val, label]) => (
                    <button
                      key={val}
                      onClick={() => setH('loanMethod', val)}
                      style={{
                        padding: '5px 12px', fontSize: 12, borderRadius: 4, cursor: 'pointer', border: 'none',
                        background: loanMethod === val ? '#000' : '#f0f0f0',
                        color: loanMethod === val ? '#fff' : '#000', fontWeight: 600,
                      }}
                    >{label}</button>
                  ))}
                </div>
              </div>

              <LinkedRow label="Purchase Price" sub={links.hmPurchase ? 'Synced to accepted price' : 'Custom'} linked={links.hmPurchase} value={hi.purchasePrice} onChange={(v) => setLinked('hmPurchase', 'purchasePrice', v)} onToggle={() => toggle('hmPurchase')} />
              <LinkedRow label="Rehab Budget" sub={links.hmRehab ? 'Synced to rehab total' : 'Custom'} linked={links.hmRehab} value={hi.rehab} onChange={(v) => setLinked('hmRehab', 'rehab', v)} onToggle={() => toggle('hmRehab')} />

              {loanMethod === 'ltc' ? (
                <React.Fragment>
                  <LinkedRow label="After Repair Value" sub={links.hmArv ? 'Synced to ARV / sale price' : 'Custom'} linked={links.hmArv} value={hi.arv} onChange={(v) => setLinked('hmArv', 'arv', v)} onToggle={() => toggle('hmArv')} />
                  <div className="fs-row"><label>Loan to Cost<small>% of purchase + rehab</small></label><NumInput value={h.ltcPct} onChange={(v) => setH('ltcPct', v || 0)} suffix="%" /></div>
                  <div className="fs-row"><label>ARV Cap<small>Max % of ARV lent</small></label><NumInput value={h.arvCapPct} onChange={(v) => setH('arvCapPct', v || 0)} suffix="%" /></div>
                </React.Fragment>
              ) : (
                <div className="fs-row">
                  <label>Down Payment<small>% of Purchase + Rehab</small></label>
                  <NumInput value={h.downPaymentPct || 20} onChange={(v) => setH('downPaymentPct', v || 0)} suffix="%" />
                </div>
              )}

              <div className="fs-row"><label>Points<small>Origination fee</small></label><NumInput value={h.points} onChange={(v) => setH('points', v || 0)} suffix="pts" /></div>
              <div className="fs-row"><label>Lender Origination<small>% of loan</small></label><NumInput value={ex.originationPct} onChange={(v) => setEx('originationPct', v || 0)} suffix="%" /></div>
              <div className="fs-row"><label>Processing / Junk Fees</label><MoneyInput value={ex.processingFee} onChange={(v) => setEx('processingFee', v)} /></div>
              <div className="fs-row"><label>Rehab Draws<small>Number of releases</small></label><NumInput value={ex.draws} onChange={(v) => setEx('draws', v || 1)} suffix="draws" /></div>
              <div className="fs-row"><label>Interest Rate</label><NumInput value={h.rate} onChange={(v) => setH('rate', v || 0)} suffix="%" /></div>
              <div className="fs-row"><label>Term</label><NumInput value={h.termMonths} onChange={(v) => setH('termMonths', v || 0)} suffix="months" /></div>
            </div>
          </div>
        </div>

        <div>
          <div className="fin-result">
            <div className="big-lbl">{loanLabel}</div>
            <div className="big-num">{fmtMoney(r.loan)}</div>
            <div className="fin-breakdown">
              {loanMethod === 'downpayment' ? (
                <React.Fragment>
                  <div className="fb"><span className="fl">Purchase Price</span><span className="fv">{fmtMoney(hi.purchasePrice)}</span></div>
                  <div className="fb"><span className="fl">Rehab Budget</span><span className="fv">{fmtMoney(hi.rehab)}</span></div>
                  <div className="fb"><span className="fl">All-in Cost</span><span className="fv">{fmtMoney(hi.purchasePrice + hi.rehab)}</span></div>
                  <div className="fb"><span className="fl">Down Payment ({r.downPaymentPct}%)</span><span className="fv" style={{ color: 'var(--coral)' }}>−{fmtMoney(r.downPaymentAmt)}</span></div>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <div className="fb"><span className="fl">{h.ltcPct}% of cost (LTC)</span><span className="fv">{fmtMoney(r.loanByLTC)}</span></div>
                  <div className="fb"><span className="fl">{h.arvCapPct}% of ARV cap</span><span className="fv">{fmtMoney(r.loanByARV)}</span></div>
                  <div className="fb"><span className="fl">Loan used (lesser)</span><span className="fv">{fmtMoney(r.loan)}</span></div>
                </React.Fragment>
              )}
              <div className="fb"><span className="fl">Points cost ({h.points} pts)</span><span className="fv">{fmtMoney(r.pointsCost)}</span></div>
              <div className="fb"><span className="fl">Monthly interest</span><span className="fv">{fmtMoney(r.monthlyInterest)}</span></div>
              <div className="fb"><span className="fl">Total interest ({h.termMonths} mo)</span><span className="fv">{fmtMoney(r.totalInterest)}</span></div>
              <div className="fb total"><span className="fl">Total financing cost</span><span className="fv">{fmtMoney(r.totalFinanceCost)}</span></div>
            </div>
          </div>
          <div className="kpi-strip" style={{ gridTemplateColumns: '1fr 1fr 1fr' }}>
            <div className="kpi accent"><div className="l">Cash to Close</div><div className="v">{fmtMoney(r.cashToClose + originationCost + (ex.processingFee || 0))}</div><div className="hint">Gap + all upfront fees</div></div>
            <div className="kpi"><div className="l">Monthly Interest</div><div className="v">{fmtMoney(r.monthlyInterest)}</div><div className="hint">Interest-only</div></div>
            <div className="kpi"><div className="l">True Cost of Capital</div><div className="v">{fmtMoney(trueCost)}</div><div className="hint">Points + orig + fees + interest</div></div>
          </div>
        </div>
      </div>

      <div className="card" style={{ marginTop: 16 }}>
        <div className="card-head"><h3>True Cost Breakdown</h3><span className="head-total">{fmtMoney(trueCost)}</span></div>
        <div className="card-body">
          <div className="term-sheet">
            <div className="term-cell"><div className="l">Points ({h.points})</div><div className="v">{fmtMoney(r.pointsCost)}</div></div>
            <div className="term-cell"><div className="l">Origination ({ex.originationPct}%)</div><div className="v">{fmtMoney(originationCost)}</div></div>
            <div className="term-cell"><div className="l">Processing / junk</div><div className="v">{fmtMoney(ex.processingFee)}</div></div>
            <div className="term-cell"><div className="l">Interest ({h.termMonths} mo)</div><div className="v" style={{ color: 'var(--coral)' }}>{fmtMoney(r.totalInterest)}</div></div>
          </div>
        </div>
      </div>

      <div className="card" style={{ marginTop: 16 }}>
        <div className="card-head"><h3>Term Sheet &amp; Interest-Only Schedule</h3></div>
        <div className="card-body">
          <TermSheet cells={[
            { l: 'Monthly Interest', v: fmtMoney(r.monthlyInterest) },
            { l: 'Points / Origination', v: fmtMoney(r.pointsCost), color: 'var(--coral)' },
            { l: 'Total Interest', v: fmtMoney(r.totalInterest), color: 'var(--coral)' },
            { l: 'Balloon @ Payoff', v: fmtMoney(r.loan) + ' · mo ' + h.termMonths },
          ]} />
          <ScheduleTable rows={sched.rows} interestOnly />
        </div>
      </div>

      <div className="card" style={{ marginTop: 16 }}>
        <div className="card-head"><h3>Rehab Draw Schedule</h3><span className="head-total">{drawCount} draws · {fmtMoney(hi.rehab)}</span></div>
        <div className="card-body" style={{ padding: 0 }}>
          <table className="cmp-tbl"><thead><tr><th>Draw</th><th>~ Month</th><th>Amount</th><th>Cumulative</th></tr></thead>
            <tbody>
              {drawRows.map((d) => (
                <tr key={d.n}><td>Draw {d.n}</td><td>Month {d.month}</td><td>{fmtMoney(d.amount)}</td><td>{fmtMoney(d.cumulative)}</td></tr>
              ))}
            </tbody>
          </table>
          <div style={{ padding: '10px 14px', fontSize: 11.5, color: 'var(--muted)', lineHeight: 1.5 }}>Lenders reimburse rehab in draws after inspection — you front each phase, then get repaid. Plan working capital for at least the first draw.</div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MortgageCalc, HardMoneyCalc, ScheduleTable, TermSheet });
