// inputs.jsx — Input panel for the mortgage calculator.
// Reuses the Aurora Glass control styles. Exports to window.

const { useState: useStateInputs } = React;
const ME_IN = window.MortgageEngine;

function CurrencyInput({ label, value, onChange, step = 1000, min = 0, max = 5000000, prefix = '£' }) {
  return (
    <div className="input-row">
      <label>{label}</label>
      <div style={{ position: 'relative' }}>
        <span style={{
          position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)',
          color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', fontSize: 14, pointerEvents: 'none'
        }}>{prefix}</span>
        <input className="input" type="number" value={value}
          step={step} min={min} max={max}
          onChange={(e) => onChange(Number(e.target.value) || 0)}
          style={{ paddingLeft: 24 }} />
      </div>
    </div>
  );
}

function SliderInput({ label, value, onChange, min, max, step = 1, unit = '', format, accent }) {
  const disp = format ? format(value) : `${value}${unit}`;
  return (
    <div className="slider-row">
      <div className="head">
        <label>{label}</label>
        <span className="val" style={accent ? { color: accent } : null}>{disp}</span>
      </div>
      <input type="range" min={min} max={max} step={step}
        value={value} onChange={(e) => onChange(Number(e.target.value))} />
    </div>
  );
}

function Segmented({ value, onChange, options }) {
  return (
    <div className="seg" style={{ width: '100%' }}>
      {options.map((o) => (
        <button key={o.v} className={value === o.v ? 'active' : ''}
          onClick={() => onChange(o.v)} style={{ flex: 1 }}>{o.l}</button>
      ))}
    </div>
  );
}

function InputsPanel({ inputs, setInputs }) {
  const set = (k) => (v) => setInputs({ ...inputs, [k]: v });
  const loan = Math.max(0, inputs.propertyPrice - inputs.deposit);
  const ltv = inputs.propertyPrice > 0 ? (loan / inputs.propertyPrice) * 100 : 0;
  const depositPct = inputs.propertyPrice > 0 ? (inputs.deposit / inputs.propertyPrice) * 100 : 0;

  // ERC headroom: penalty-free overpayment is ~10%/yr of the balance.
  const annualOverpay = inputs.monthlyOverpay * 12;
  const ercCap = loan * 0.10;
  const ercBreach = annualOverpay > ercCap;

  return (
    <div className="stack" style={{ width: "340px" }}>
      <div className="card card-pad-sm">
        <h3 className="card-title">Property &amp; deposit</h3>
        <p className="card-sub">What you're buying</p>
        <div className="grid grid-2">
          <CurrencyInput label="Property price" value={inputs.propertyPrice}
            onChange={set('propertyPrice')} step={5000} max={3000000} />
          <CurrencyInput label="Deposit" value={inputs.deposit}
            onChange={set('deposit')} step={1000} max={2000000} />
        </div>
        <div className="div-h" />
        <div className="balance-strip">
          <span style={{ fontSize: 12, color: 'var(--ink-2)' }}>Loan amount</span>
          <span className="num" style={{ fontSize: 14 }}>{ME_IN.fmtGBP(loan, 'short')}</span>
        </div>
        <div className="balance-strip">
          <span style={{ fontSize: 12, color: 'var(--ink-2)' }}>Loan-to-value (LTV)</span>
          <span className="num" style={{ fontSize: 14, color: ltv > 90 ? 'var(--c-warn)' : 'var(--c-invest)' }}>{ltv.toFixed(0)}%</span>
        </div>
        <div className="balance-strip">
          <span style={{ fontSize: 12, color: 'var(--ink-2)' }}>Deposit</span>
          <span className="num" style={{ fontSize: 14 }}>{depositPct.toFixed(0)}%</span>
        </div>
      </div>

      <div className="card card-pad-sm">
        <h3 className="card-title">The mortgage</h3>
        <p className="card-sub">Type, term &amp; rate</p>
        <div className="input-row" style={{ marginBottom: 14 }}>
          <label>Repayment basis</label>
          <Segmented value={inputs.mortgageType} onChange={set('mortgageType')}
            options={[{ v: 'repayment', l: 'Repayment' }, { v: 'interest-only', l: 'Interest-only' }]} />
        </div>
        <SliderInput label="Term" value={inputs.termYears} min={5} max={40} step={1}
          onChange={set('termYears')} format={(v) => `${v} yrs`} />
        <div style={{ height: 14 }} />
        <SliderInput label="Fixed rate" value={inputs.fixedRate * 100} min={0.5} max={10} step={0.05}
          onChange={(v) => set('fixedRate')(v / 100)} format={(v) => `${v.toFixed(2)}%`} accent="var(--c-overpay)" />
        <div style={{ height: 12 }} />
        <SliderInput label="Fixed for" value={inputs.fixedYears} min={0} max={10} step={1}
          onChange={set('fixedYears')} format={(v) => v === 0 ? 'No fix' : `${v} yrs`} />
        <div style={{ height: 12 }} />
        <SliderInput label="Reverts to (SVR)" value={inputs.revertRate * 100} min={1} max={12} step={0.05}
          onChange={(v) => set('revertRate')(v / 100)} format={(v) => `${v.toFixed(2)}%`} accent="var(--c-warn)" />
      </div>

      <div className="card card-pad-sm">
        <h3 className="card-title">Extra payments</h3>
        <p className="card-sub">What you'd overpay — or invest instead</p>
        <SliderInput label="Monthly overpayment / invested"
          value={inputs.monthlyOverpay} min={0} max={2000} step={25}
          onChange={set('monthlyOverpay')} format={(v) => `£${v} / mo`} accent="var(--c-invest)" />
        {ercBreach && (
          <div style={{
            marginTop: 10, padding: '9px 11px', borderRadius: 10,
            background: 'color-mix(in oklab, var(--c-warn) 14%, transparent)',
            border: '1px solid color-mix(in oklab, var(--c-warn) 40%, transparent)',
            fontSize: 11.5, color: 'var(--ink-1)', lineHeight: 1.4,
          }}>
            <b style={{ color: 'var(--c-warn)' }}>Over the 10% allowance.</b> You'd overpay {ME_IN.fmtGBP(annualOverpay, 'short')}/yr;
            most fixed deals only allow {ME_IN.fmtGBP(ercCap, 'short')} penalty-free. The excess may trigger an early repayment charge.
          </div>
        )}
        <div style={{ height: 14 }} />
        <CurrencyInput label="One-off lump sum (today)" value={inputs.lumpSum}
          onChange={set('lumpSum')} step={1000} max={500000} />
        <div style={{ height: 14 }} />
        <div className="input-row">
          <label>After the lump sum, the £{inputs.monthlyOverpay}/mo…</label>
          <Segmented value={inputs.lumpThenAction} onChange={set('lumpThenAction')}
            options={[{ v: 'overpay', l: 'Overpays' }, { v: 'invest', l: 'Invests' }, { v: 'none', l: 'Nothing' }]} />
        </div>
      </div>

      <div className="card card-pad-sm">
        <h3 className="card-title">Invest instead?</h3>
        <p className="card-sub">What the same money could earn in the market</p>
        <SliderInput label="Expected annual return"
          value={inputs.investReturn * 100} min={2} max={12} step={0.25}
          onChange={(v) => set('investReturn')(v / 100)} format={(v) => `${v.toFixed(2)}% / yr`} accent="var(--c-invest)" />
        <div style={{ height: 12 }} />
        <SliderInput label="Inflation"
          value={inputs.inflation * 100} min={0} max={8} step={0.25}
          onChange={(v) => set('inflation')(v / 100)} format={(v) => `${v.toFixed(2)}% / yr`} />
        <div style={{ height: 12 }} />
        <SliderInput label="Platform fees"
          value={inputs.investFee * 100} min={0} max={2} step={0.05}
          onChange={(v) => set('investFee')(v / 100)} format={(v) => `${v.toFixed(2)}% / yr`} />
      </div>

      <div className="card card-pad-sm">
        <h3 className="card-title">Affordability &amp; stamp duty</h3>
        <p className="card-sub">Sense-check the purchase</p>
        <CurrencyInput label="Household income (gross / yr)" value={inputs.income}
          onChange={set('income')} step={1000} max={1000000} />
        <div style={{ height: 14 }} />
        <div className="input-row">
          <label>First-time buyer?</label>
          <Segmented value={inputs.firstTimeBuyer ? 'yes' : 'no'}
            onChange={(v) => set('firstTimeBuyer')(v === 'yes')}
            options={[{ v: 'yes', l: 'Yes' }, { v: 'no', l: 'No' }]} />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { InputsPanel, CurrencyInput, SliderInput, Segmented });
