// Net worth — assets minus liabilities, projected over time.

const PageNetWorth = () => {
  const { state, derived } = useAppState();
  const { totalDebt, totalGoals, months } = derived;

  // Crude model: assets = goals saved + cash buffer (cumulative net surplus).
  // Project net worth over last 6 months using monthly net.
  const netHistory = [];
  let cumulative = totalGoals;
  // Walk backwards: subtract last 5 months' net
  const reversed = [...months].reverse();
  reversed.forEach((m, i) => {
    netHistory.unshift({ label: m.label, value: cumulative - totalDebt });
    cumulative -= m.net;
  });
  // Push forward today's value
  const currentNetWorth = totalGoals - totalDebt;

  // Project 12 months ahead using avg monthly surplus
  const avgSurplus = months.reduce((a, m) => a + m.net, 0) / Math.max(1, months.length);
  const future = [];
  let projected = currentNetWorth;
  for (let i = 1; i <= 12; i++) {
    projected += avgSurplus;
    future.push({ label: monthNames[(today().getMonth() + i) % 12], value: projected });
  }

  const allPoints = [...netHistory, { label: 'Now', value: currentNetWorth }, ...future];
  const maxV = Math.max(...allPoints.map(p => p.value), 1);
  const minV = Math.min(...allPoints.map(p => p.value), 0);
  const range = maxV - minV || 1;

  const width = 700, height = 240;
  const pad = { l: 50, r: 16, t: 16, b: 28 };
  const w = width - pad.l - pad.r;
  const h = height - pad.t - pad.b;
  const x = (i) => pad.l + (w * i) / Math.max(1, allPoints.length - 1);
  const y = (v) => pad.t + h - ((v - minV) / range) * h;

  const linePath = allPoints.map((p, i) => `${i === 0 ? 'M' : 'L'} ${x(i)} ${y(p.value)}`).join(' ');
  const areaPath = `${linePath} L ${x(allPoints.length - 1)} ${pad.t + h} L ${x(0)} ${pad.t + h} Z`;
  const nowIdx = netHistory.length;

  if (state.transactions.length === 0 && state.debts.length === 0 && state.goals.length === 0) {
    return (
      <div>
        <div className="topbar">
          <div>
            <h1 className="page-title">Net worth</h1>
            <div className="page-sub">Assets minus debts, over time</div>
          </div>
        </div>
        <div className="empty">
          <div className="empty-icon"><ITrend size={22}/></div>
          <h3 className="serif" style={{fontSize:22}}>Add some data</h3>
          <p>Track savings, debts and transactions and we'll project your net worth over time.</p>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="topbar">
        <div>
          <h1 className="page-title"><span className="serif">Net</span> worth</h1>
          <div className="page-sub">Assets minus liabilities · projected 12 months</div>
        </div>
      </div>

      <div className="grid" style={{gridTemplateColumns:'repeat(3, 1fr)', gap:16, marginBottom:20}}>
        <KPICard label="Net worth (now)" value={currentNetWorth} icon={ITrend} accent={currentNetWorth >= 0 ? 'mint' : 'coral'}/>
        <KPICard label="Assets" value={totalGoals} icon={ISavings} accent="mint" sub="Savings goals"/>
        <KPICard label="Liabilities" value={totalDebt} icon={IDebt} accent="coral" sub="Outstanding debts"/>
      </div>

      <div className="card card-pad-lg fade-up" style={{marginBottom:20}}>
        <div className="card-title row-between">
          <span>Trajectory · 6 months back, 12 forward</span>
          <span className="row" style={{fontSize:11, color:'var(--ink-3)', gap:14}}>
            <span className="row" style={{gap:5}}><span className="dot" style={{background:'var(--ink)'}}></span> Actual</span>
            <span className="row" style={{gap:5}}><span style={{width:14, height:2, background:'var(--ink-4)', borderRadius:1, borderTop:'1px dashed var(--ink-4)'}}></span> Projected</span>
          </span>
        </div>
        <svg width={width} height={height} style={{display:'block', maxWidth:'100%'}}>
          <defs>
            <linearGradient id="nwGrad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="var(--mint)" stopOpacity="0.25"/>
              <stop offset="100%" stopColor="var(--mint)" stopOpacity="0"/>
            </linearGradient>
          </defs>

          {/* Zero line */}
          {minV < 0 && maxV > 0 && (
            <line x1={pad.l} x2={pad.l + w} y1={y(0)} y2={y(0)} stroke="var(--line)" strokeDasharray="2 4"/>
          )}

          <path d={areaPath} fill="url(#nwGrad)" style={{opacity:0, animation:'fadeIn 0.6s 0.4s forwards'}}/>

          {/* Historical (solid) */}
          <path
            d={netHistory.concat([{ label:'Now', value: currentNetWorth }]).map((p, i) => `${i===0?'M':'L'} ${x(i)} ${y(p.value)}`).join(' ')}
            fill="none" stroke="var(--ink)" strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round"
            className="draw-line" style={{'--draw-len': 1500}}
          />
          {/* Future (dashed) */}
          <path
            d={[{ label:'Now', value: currentNetWorth }, ...future].map((p, i) => `${i===0?'M':'L'} ${x(i + nowIdx)} ${y(p.value)}`).join(' ')}
            fill="none" stroke="var(--ink-4)" strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round"
            strokeDasharray="4 5"
            style={{opacity:0, animation:'fadeIn 0.6s 1.2s forwards'}}
          />

          {/* Now marker */}
          <circle cx={x(nowIdx)} cy={y(currentNetWorth)} r="5" fill="var(--ink)" stroke="white" strokeWidth="2"
            style={{opacity:0, animation:'fadeIn 0.4s 1.4s forwards'}}/>
          <text x={x(nowIdx)} y={y(currentNetWorth) - 12} textAnchor="middle" fontSize="10" fill="var(--ink-3)" className="mono"
            style={{opacity:0, animation:'fadeIn 0.4s 1.4s forwards'}}>Now</text>

          {/* X labels */}
          {allPoints.map((p, i) => i % 3 === 0 && (
            <text key={i} x={x(i)} y={height - 8} fontSize="10" fill="var(--ink-3)" textAnchor="middle" className="mono">{p.label}</text>
          ))}
          {/* Y labels */}
          {[minV, (minV+maxV)/2, maxV].map((v, i) => (
            <text key={i} x={pad.l - 8} y={y(v) + 3} fontSize="10" fill="var(--ink-3)" textAnchor="end" className="mono">{fmtZARShort(v)}</text>
          ))}
        </svg>

        {avgSurplus !== 0 && (
          <div style={{marginTop:14, padding:'12px 14px', background:'var(--surface-2)', borderRadius:10, fontSize:13, color:'var(--ink-2)'}}>
            <strong>At your current pace</strong>, you'll {avgSurplus > 0 ? 'add' : 'lose'} about <span className="mono" style={{fontWeight:500, color:'var(--ink)'}}>{fmtZARShort(Math.abs(avgSurplus))}</span> per month to your net worth — {avgSurplus > 0 ? 'a projected' : 'down to'} <span className="mono" style={{fontWeight:500, color:'var(--ink)'}}>{fmtZARShort(future[future.length - 1].value)}</span> in 12 months.
          </div>
        )}
      </div>

      {/* Asset/liability breakdown */}
      <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:20}}>
        <div className="card card-pad-lg fade-up" style={{animationDelay:'0.1s'}}>
          <div className="card-title">Assets</div>
          {state.goals.length === 0 ? <div style={{color:'var(--ink-3)', fontSize:13}}>None tracked.</div> :
            state.goals.map((g, i) => (
              <div key={g.id} className="row-between" style={{padding:'10px 0', borderBottom: i === state.goals.length - 1 ? 'none' : '1px solid var(--line-2)'}}>
                <div className="row" style={{gap:8}}>
                  <span className="dot" style={{background:'var(--mint)'}}></span>
                  <span style={{fontSize:13.5}}>{g.name}</span>
                </div>
                <span className="mono" style={{fontWeight:500}}>{fmtZAR(g.saved, {cents:false})}</span>
              </div>
            ))
          }
        </div>
        <div className="card card-pad-lg fade-up" style={{animationDelay:'0.15s'}}>
          <div className="card-title">Liabilities</div>
          {state.debts.length === 0 ? <div style={{color:'var(--ink-3)', fontSize:13}}>None — well done.</div> :
            state.debts.map((d, i) => (
              <div key={d.id} className="row-between" style={{padding:'10px 0', borderBottom: i === state.debts.length - 1 ? 'none' : '1px solid var(--line-2)'}}>
                <div className="row" style={{gap:8}}>
                  <span className="dot" style={{background:'var(--coral)'}}></span>
                  <span style={{fontSize:13.5}}>{d.name}</span>
                </div>
                <span className="mono" style={{fontWeight:500}}>−{fmtZAR(d.balance, {cents:false})}</span>
              </div>
            ))
          }
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { PageNetWorth });
