/* FinPulse — Calculators (SIP / Lumpsum / SWP). Exports CalcScreen to window. */
const INR = (n) => '₹' + Math.round(n).toLocaleString('en-IN');

function CalcSlider({ label, value, min, max, step, onChange, fmtv }) {
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div style={{ marginBottom: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <span style={{ fontSize: 13, color: 'var(--text-secondary)', fontWeight: 500 }}>{label}</span>
        <span className="calc-val">{fmtv(value)}</span>
      </div>
      <input className="calc-range" type="range" min={min} max={max} step={step} value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        style={{ background: `linear-gradient(90deg, var(--accent) ${pct}%, var(--border) ${pct}%)` }} />
    </div>
  );
}

function DonutResult({ invested, gains }) {
  const total = invested + gains;
  const r = 52, c = 2 * Math.PI * r;
  const gFrac = total > 0 ? gains / total : 0;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
      <svg width="130" height="130" viewBox="0 0 130 130" style={{ flexShrink: 0 }}>
        <circle cx="65" cy="65" r={r} fill="none" stroke="var(--accent)" strokeWidth="16" opacity="0.25" />
        <circle cx="65" cy="65" r={r} fill="none" stroke="var(--accent)" strokeWidth="16"
          strokeDasharray={`${c * gFrac} ${c}`} strokeDashoffset={c * 0.25} transform="rotate(-90 65 65)" strokeLinecap="round"
          style={{ transition: 'stroke-dasharray 0.4s ease' }} />
        <text x="65" y="60" textAnchor="middle" style={{ fontSize: 11, fill: 'var(--text-muted)', fontFamily: 'var(--font-body)' }}>Gains</text>
        <text x="65" y="78" textAnchor="middle" style={{ fontSize: 16, fill: 'var(--text-primary)', fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{Math.round(gFrac * 100)}%</text>
      </svg>
      <div style={{ flex: 1, minWidth: 160 }}>
        <div className="calc-legend"><span className="dot" style={{ background: 'var(--accent)', opacity: 0.25 }}></span>Invested<span className="lv">{INR(invested)}</span></div>
        <div className="calc-legend"><span className="dot" style={{ background: 'var(--accent)' }}></span>Est. returns<span className="lv">{INR(gains)}</span></div>
        <div className="calc-legend total"><span>Total value</span><span className="lv">{INR(total)}</span></div>
      </div>
    </div>
  );
}

function CalcScreen() {
  const [tab, setTab] = useState('sip');
  const [monthly, setMonthly] = useState(15000);
  const [lump, setLump] = useState(500000);
  const [rate, setRate] = useState(12);
  const [years, setYears] = useState(10);
  const [withdraw, setWithdraw] = useState(20000);

  // SIP future value
  const months = years * 12;
  const i = rate / 100 / 12;
  let invested, total, series = [];
  if (tab === 'sip') {
    total = monthly * ((Math.pow(1 + i, months) - 1) / (i || 1)) * (1 + i);
    invested = monthly * months;
    for (let y = 1; y <= years; y++) { const m = y * 12; series.push(monthly * ((Math.pow(1 + i, m) - 1) / (i || 1)) * (1 + i)); }
  } else if (tab === 'lump') {
    total = lump * Math.pow(1 + rate / 100, years);
    invested = lump;
    for (let y = 1; y <= years; y++) series.push(lump * Math.pow(1 + rate / 100, y));
  } else { // SWP
    invested = lump;
    let bal = lump;
    for (let y = 1; y <= years; y++) {
      for (let m = 0; m < 12; m++) { bal = bal * (1 + i) - withdraw; }
      series.push(Math.max(bal, 0));
    }
    total = Math.max(bal, 0);
  }
  const gains = Math.max(total - invested, 0);

  return (
    <div>
      <div style={{ marginBottom: 14 }}>
        <h1 className="h1">Calculators</h1>
        <div className="muted" style={{ marginTop: 2 }}>Plan SIPs, lumpsum growth &amp; systematic withdrawals</div>
      </div>

      <div className="seg section" style={{ width: 'fit-content' }}>
        {[['sip', 'SIP'], ['lump', 'Lumpsum'], ['swp', 'SWP']].map(([k, l]) => (
          <button key={k} className={`seg-btn ${tab === k ? 'on' : ''}`} onClick={() => setTab(k)}>{l}</button>
        ))}
      </div>

      <div className="detail-grid">
        {/* inputs */}
        <div className="card">
          {tab === 'sip' && <CalcSlider label="Monthly investment" value={monthly} min={500} max={200000} step={500} onChange={setMonthly} fmtv={INR} />}
          {(tab === 'lump' || tab === 'swp') && <CalcSlider label={tab === 'swp' ? 'Total corpus' : 'Investment amount'} value={lump} min={10000} max={10000000} step={10000} onChange={setLump} fmtv={INR} />}
          {tab === 'swp' && <CalcSlider label="Monthly withdrawal" value={withdraw} min={1000} max={200000} step={1000} onChange={setWithdraw} fmtv={INR} />}
          <CalcSlider label="Expected return (p.a.)" value={rate} min={1} max={30} step={0.5} onChange={setRate} fmtv={(v) => v + '%'} />
          <CalcSlider label="Time period" value={years} min={1} max={40} step={1} onChange={setYears} fmtv={(v) => v + (v === 1 ? ' yr' : ' yrs')} />

          <div style={{ borderTop: '1px solid var(--border)', paddingTop: 18, marginTop: 4 }}>
            <DonutResult invested={invested} gains={gains} />
          </div>
        </div>

        {/* projection chart */}
        <div className="card">
          <h3 className="h3" style={{ marginBottom: 4 }}>{tab === 'swp' ? 'Corpus over time' : 'Projected growth'}</h3>
          <div className="muted" style={{ marginBottom: 12 }}>{tab === 'swp' ? 'Balance after monthly withdrawals' : `Value after ${years} years`}</div>
          <AreaChart key={tab + years} data={series.length > 1 ? series : [0, ...series]} color="var(--accent)" height={200}
            labels={['Yr 1', '', `Yr ${Math.ceil(years / 2)}`, '', `Yr ${years}`]} />
          <div className="kv" style={{ borderBottom: '1px solid var(--border)' }}><span className="k">Invested</span><span className="v">{INR(invested)}</span></div>
          <div className="kv" style={{ borderBottom: '1px solid var(--border)' }}><span className="k">{tab === 'swp' ? 'Total withdrawn' : 'Est. returns'}</span><span className="v" style={{ color: 'var(--up)' }}>{tab === 'swp' ? INR(withdraw * months) : INR(gains)}</span></div>
          <div className="kv" style={{ borderBottom: 'none' }}><span className="k" style={{ fontWeight: 600, color: 'var(--text-primary)' }}>{tab === 'swp' ? 'Balance left' : 'Total value'}</span><span className="v" style={{ fontSize: 16 }}>{INR(total)}</span></div>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { CalcScreen });
