// app.jsx — Main shell + state for the Mortgage Strategy app.

const { useState: useStateApp, useMemo: useMemoApp, useEffect: useEffectApp } = React;
const MEng = window.MortgageEngine;

const NAV = [
  { key: 'dashboard', label: 'Dashboard' },
  { key: 'calculator', label: 'Calculator' },
  { key: 'charts', label: 'Charts' },
];

const DEFAULTS = {
  propertyPrice: 250000,
  deposit: 25000,            // 10% → £225k loan
  termYears: 30,
  mortgageType: 'repayment',
  fixedRate: 0.045,
  fixedYears: 5,
  revertRate: 0.075,
  monthlyOverpay: 250,
  lumpSum: 5000,
  lumpThenAction: 'overpay',
  investReturn: 0.07,
  inflation: 0.025,
  investFee: 0.0025,
  income: 55000,
  firstTimeBuyer: true,
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "fmtMode": "short",
  "chartStyle": "area"
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [screen, setScreen] = useStateApp('dashboard');
  const [inputs, setInputs] = useStateApp(DEFAULTS);

  useEffectApp(() => {
    document.documentElement.setAttribute('data-theme', 'dark');
    const gnav = document.querySelector('global-nav');
    if (gnav) gnav.setAttribute('theme', 'dark');
  }, []);

  const base = useMemoApp(() => window.baseFromInputs(inputs), [inputs]);
  const results = useMemoApp(() => MEng.compareStrategies(base), [base]);
  const reco = useMemoApp(() => MEng.recommend(results, { ...inputs, balance: base.balance }), [results, inputs, base.balance]);

  const loan = Math.max(0, inputs.propertyPrice - inputs.deposit);
  const monthly = results.standard.scheduledMonthly;

  function exportReport() {
    const std = results.standard, ovr = results.overpay, lump = results.lump, inv = results.invest;
    const netWorth = (s) => s.finalInvested - s.finalBalance;
    const sdlt = MEng.stampDuty(inputs.propertyPrice, inputs.firstTimeBuyer);
    const payoff = (s) => s.payoffMonth == null
      ? (s.type === 'interest-only' ? 'Capital due at term end' : `Year ${inputs.termYears}`)
      : (s.payoffMonth === 0 ? 'Cleared today' : `Year ${(s.payoffMonth / 12).toFixed(1)}`);
    const g = (n) => MEng.fmtGBP(n, 'full');
    window.PremiumReport.generate({
      tool: 'Mortgage Strategy',
      accent: '#d98a45',
      scenario: `${g(loan)} ${inputs.mortgageType === 'repayment' ? 'repayment' : 'interest-only'} mortgage · ${(inputs.fixedRate * 100).toFixed(2)}% fixed ${inputs.fixedYears}y → ${(inputs.revertRate * 100).toFixed(2)}% · ${inputs.termYears}-year term`,
      verdict: reco ? { line: reco.headline, reasoning: reco.reasoning } : null,
      metrics: [
        { label: 'Monthly payment (fixed)', value: g(monthly) },
        { label: 'Total interest (standard)', value: g(std.totalInterest) },
        { label: 'Stamp duty', value: g(sdlt) },
        { label: 'Interest saved by overpaying', value: g(std.totalInterest - ovr.totalInterest), accent: '#7b54c8' },
        { label: 'Investment pot instead', value: g(inv.finalInvested), accent: '#1f8a6d' },
        { label: 'Net advantage', value: (netWorth(inv) > netWorth(ovr) ? '+' : '') + g(netWorth(inv) - netWorth(ovr)) },
      ],
      chartTitle: 'Mortgage balance over time — overpay vs standard',
      chartSVG: window.PremiumReport.captureSVG('.main .card svg'),
      tables: [{
        title: 'Strategy comparison',
        headers: ['Strategy', 'Net wealth', 'Interest paid', 'Mortgage-free', 'Portfolio'],
        rows: [
          ['Standard', g(netWorth(std)), g(std.totalInterest), payoff(std), g(std.finalInvested)],
          ['Monthly overpay', g(netWorth(ovr)), g(ovr.totalInterest), payoff(ovr), g(ovr.finalInvested)],
          ['Lump sum', g(netWorth(lump)), g(lump.totalInterest), payoff(lump), g(lump.finalInvested)],
          ['Invest instead', g(netWorth(inv)), g(inv.totalInterest), payoff(inv), g(inv.finalInvested)],
        ],
        highlightRow: { standard: 0, overpay: 1, lump: 2, invest: 3 }[reco.best],
      }],
      notes: [
        reco.investWins
          ? 'On your assumptions, investing the spare cash beats overpaying — but it carries market risk, whereas overpaying is a guaranteed, tax-free return equal to your mortgage rate.'
          : 'On your assumptions, overpaying wins — a guaranteed return equal to your mortgage rate, and you clear the debt sooner.',
        inputs.mortgageType === 'interest-only'
          ? 'This is interest-only: the standard balance never reduces, so you must have a plan to repay the full capital at the end of the term.'
          : 'Most fixed deals allow penalty-free overpayments of up to 10% of the balance per year; above that an early repayment charge may apply.',
        'Keep an emergency fund in place before overpaying or investing, and use a Stocks & Shares ISA to shelter investment gains from tax.',
      ],
    });
  }

  return (
    <React.Fragment>
      <div className="aurora"><div className="blob"></div></div>

      <div className="app" data-screen-label="Mortgage Strategy">
        <aside className="sidebar">
          <nav className="rail-nav">
            <div className="nav-group">
              <div className="nav-group-label">Strategy</div>
              {NAV.map((n) =>
                <button key={n.key}
                  className={`nav-item ${screen === n.key ? 'active' : ''}`}
                  onClick={() => setScreen(n.key)}>
                  <span className="ni-dot" />
                  <span className="ni-label">{n.label}</span>
                </button>
              )}
            </div>
            <div className="nav-group">
              <div className="nav-group-label">Scenario</div>
              <button className="nav-item" onClick={() => setInputs(DEFAULTS)}>
                <span className="ni-dot" />
                <span className="ni-label">First-time buyer</span>
                <span className="ni-tag">Default</span>
              </button>
              <button className="nav-item" onClick={() => setInputs((i) => ({
                ...DEFAULTS, propertyPrice: 350000, deposit: 100000, termYears: 25,
                monthlyOverpay: 400, income: 75000, firstTimeBuyer: false, lumpSum: 10000,
              }))}>
                <span className="ni-dot" />
                <span className="ni-label">Typical mover</span>
              </button>
              <button className="nav-item" onClick={() => setInputs((i) => ({
                ...DEFAULTS, propertyPrice: 280000, deposit: 100000, termYears: 18,
                fixedRate: 0.052, fixedYears: 2, revertRate: 0.079,
                monthlyOverpay: 300, income: 60000, firstTimeBuyer: false,
              }))}>
                <span className="ni-dot" />
                <span className="ni-label">Remortgager</span>
              </button>
              <button className="nav-item" onClick={() => setInputs((i) => ({
                ...i, mortgageType: i.mortgageType === 'repayment' ? 'interest-only' : 'repayment',
              }))}>
                <span className="ni-dot" />
                <span className="ni-label">Toggle interest-only</span>
              </button>
            </div>
          </nav>
          <div className="rail-foot">
            <div className="rail-foot-label">Current scenario</div>
            <div className="rail-foot-row"><span>Loan</span><b>{MEng.fmtGBP(loan, t.fmtMode)}</b></div>
            <div className="rail-foot-row"><span>LTV · term</span><b>{((loan / inputs.propertyPrice) * 100).toFixed(0)}% · {inputs.termYears}y</b></div>
            <div className="rail-foot-row hero"><span>Monthly</span><b>{MEng.fmtGBP(monthly, t.fmtMode)}</b></div>
            <div className="rail-foot-note">Estimate only · not advice</div>
          </div>
        </aside>

        <main className="main">
          <div className="topbar">
            <div>
              <h1>
                {screen === 'dashboard' && <>Overpay, or <span className="accent">invest the difference</span>?</>}
                {screen === 'calculator' && <>Mortgage Calculator</>}
                {screen === 'charts' && <>Charts</>}
              </h1>
              <div className="sub">
                {screen === 'dashboard' && 'Which use of your spare cash builds the most wealth by the end of the term — recalculated live.'}
                {screen === 'calculator' && 'Real UK mortgage maths — fixed→SVR rates, the 10% rule, stamp duty and affordability.'}
                {screen === 'charts' && 'The same decision, drawn out over the full term.'}
              </div>
            </div>
            <div className="topbar-actions">
              <button className="btn btn-ghost">Save scenario</button>
              <button className="btn btn-primary" onClick={exportReport}>↓ PDF report</button>
            </div>
          </div>

          {screen === 'dashboard' && <DashboardScreen inputs={inputs} results={results} reco={reco} fmtMode={t.fmtMode} chartStyle={t.chartStyle} />}
          {screen === 'calculator' && <CalculatorScreen inputs={inputs} setInputs={setInputs} results={results} fmtMode={t.fmtMode} chartStyle={t.chartStyle} />}
          {screen === 'charts' && <ChartsScreen inputs={inputs} results={results} fmtMode={t.fmtMode} chartStyle={t.chartStyle} />}
        </main>
      </div>

      <TweaksPanel>
        <TweakSection label="Display" />
        <TweakRadio label="Currency" value={t.fmtMode}
          options={[{ value: 'short', label: '£225k' }, { value: 'full', label: '£225,000' }]}
          onChange={(v) => setTweak('fmtMode', v)} />
        <TweakRadio label="Chart style" value={t.chartStyle}
          options={[{ value: 'line', label: 'Line' }, { value: 'area', label: 'Area' }]}
          onChange={(v) => setTweak('chartStyle', v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
