// Interactive SIP calculator
const fmtCr = (n) => {
  if (n >= 1e7) return `₹${(n / 1e7).toFixed(2)} Cr`;
  if (n >= 1e5) return `₹${(n / 1e5).toFixed(2)} L`;
  return `₹${Math.round(n).toLocaleString("en-IN")}`;
};
const fmtINR = (n) => `₹${Math.round(n).toLocaleString("en-IN")}`;

const Slider = ({ label, value, onChange, min, max, step, format, suffix }) => {
  const pct = Math.max(0, Math.min(100, ((value - min) / (max - min)) * 100));
  const track = `linear-gradient(to right, var(--gold-500) 0%, var(--gold-500) ${pct}%, rgba(250,246,236,0.18) ${pct}%, rgba(250,246,236,0.18) 100%)`;
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
        <span className="eyebrow" style={{ color: "var(--gold-300)" }}>{label}</span>
        <span className="mono" style={{ fontSize: 16, color: "var(--cream)" }}>
          {format ? format(value) : value}{suffix}
        </span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value} onChange={e => onChange(Number(e.target.value))}
        style={{ width: "100%", accentColor: "var(--gold-500)", background: track }}/>
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6 }}>
        <span className="mono" style={{ fontSize: 10, color: "var(--green-300)", letterSpacing: "0.12em" }}>{format ? format(min) : min}</span>
        <span className="mono" style={{ fontSize: 10, color: "var(--green-300)", letterSpacing: "0.12em" }}>{format ? format(max) : max}</span>
      </div>
    </div>
  );
};

const Calculator = () => {
  const [monthly, setMonthly] = useState(25000);
  const [years, setYears] = useState(20);
  const [rate, setRate] = useState(12);
  const [stepUp, setStepUp] = useState(8);

  const { final, invested, growth, series } = useMemo(() => {
    const r = rate / 100 / 12;
    let bal = 0, inv = 0, sip = monthly;
    const pts = [];
    for (let y = 1; y <= years; y++) {
      for (let m = 0; m < 12; m++) {
        bal = bal * (1 + r) + sip;
        inv += sip;
      }
      pts.push({ y, bal, inv });
      sip = sip * (1 + stepUp / 100);
    }
    return { final: bal, invested: inv, growth: bal - inv, series: pts };
  }, [monthly, years, rate, stepUp]);

  const W = 600, H = 260, P = 20;
  const maxY = series.length ? series[series.length - 1].bal : 1;
  const xAt = (i) => P + (i / (series.length - 1 || 1)) * (W - P * 2);
  const yAt = (v) => H - P - (v / maxY) * (H - P * 2);
  const balPath = "M " + series.map((s, i) => `${xAt(i)} ${yAt(s.bal)}`).join(" L ");
  const invPath = "M " + series.map((s, i) => `${xAt(i)} ${yAt(s.inv)}`).join(" L ");
  const balArea = balPath + ` L ${xAt(series.length - 1)} ${H - P} L ${P} ${H - P} Z`;

  return (
    <section id="calculator" className="block" style={{ background: "var(--ink)", color: "var(--cream)" }}>
      <div className="container">
        <div style={{ marginBottom: 56 }}>
          <Marker index={6} total={7} label="Plan it before you do it"/>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1.05fr 1fr", gap: 72, alignItems: "start" }} className="calc-grid">
          <div>
            <h2 className="display" style={{ fontSize: "clamp(33px, 4.2vw, 51px)", lineHeight: 1.02, marginBottom: 24, color: "var(--cream)" }}>
              What does discipline actually <span style={{ color: "var(--gold-400)" }}>buy you</span>?
            </h2>
            <p style={{ fontSize: 17, lineHeight: 1.6, color: "rgba(250,246,236,0.78)", maxWidth: 520, marginBottom: 36 }}>
              A real SIP calculator with an annual step-up — most online versions skip the step-up, which is exactly what makes a long horizon work. Move the dials.
            </p>

            <div style={{ borderTop: "1px solid var(--hairline-light)", borderBottom: "1px solid var(--hairline-light)", padding: "28px 0", marginBottom: 28 }}>
              <div className="eyebrow on-dark">Projected corpus in {years} years</div>
              <div className="display" style={{ fontSize: "clamp(49px, 6.3vw, 67px)", lineHeight: 1, color: "var(--gold-400)", marginTop: 8, fontWeight: 700 }}>
                {fmtCr(final)}
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28, marginTop: 24 }}>
                <div>
                  <div className="eyebrow on-dark">Total invested</div>
                  <div className="mono" style={{ fontSize: 22, marginTop: 8 }}>{fmtCr(invested)}</div>
                </div>
                <div>
                  <div className="eyebrow on-dark">Wealth gained</div>
                  <div className="mono" style={{ fontSize: 22, marginTop: 8, color: "var(--gold-300)" }}>{fmtCr(growth)}</div>
                </div>
              </div>
            </div>

            <div style={{ position: "relative" }}>
              <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto" }}>
                <defs>
                  <linearGradient id="ar" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0" stopColor="#FFD249" stopOpacity="0.5"/>
                    <stop offset="1" stopColor="#FFD249" stopOpacity="0"/>
                  </linearGradient>
                </defs>
                {[0.25, 0.5, 0.75].map(t => (
                  <line key={t} x1={P} x2={W - P} y1={P + t * (H - P * 2)} y2={P + t * (H - P * 2)} stroke="rgba(250,246,236,0.08)" strokeDasharray="2 4"/>
                ))}
                <path d={balArea} fill="url(#ar)"/>
                <path d={invPath} stroke="rgba(250,246,236,0.5)" strokeWidth="1.4" fill="none" strokeDasharray="3 4"/>
                <path d={balPath} stroke="#FFD249" strokeWidth="2.4" fill="none"/>
                <circle cx={xAt(series.length - 1)} cy={yAt(series[series.length - 1].bal)} r="5" fill="#FFD249"/>
                <circle cx={xAt(series.length - 1)} cy={yAt(series[series.length - 1].bal)} r="10" fill="none" stroke="#FFD249" strokeOpacity="0.3"/>
              </svg>
              <div style={{ display: "flex", gap: 24, marginTop: 16 }}>
                <span className="mono" style={{ fontSize: 11, color: "var(--gold-400)", letterSpacing: "0.12em" }}>━ CORPUS</span>
                <span className="mono" style={{ fontSize: 11, color: "rgba(250,246,236,0.6)", letterSpacing: "0.12em" }}>┄ INVESTED</span>
              </div>
            </div>
          </div>

          <div style={{ background: "var(--green-800)", padding: 36, border: "1px solid var(--hairline-light)", position: "sticky", top: 100, borderRadius: 8 }} className="calc-panel">
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 24 }}>
              <h3 className="display" style={{ fontSize: 24, color: "var(--cream)", fontWeight: 700 }}>SIP Calculator</h3>
              <span className="mono" style={{ fontSize: 10, color: "var(--gold-300)", letterSpacing: "0.14em" }}>STEP-UP ENABLED</span>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
              <Slider label="Monthly investment" value={monthly} onChange={setMonthly} min={1000} max={500000} step={1000} format={fmtINR}/>
              <Slider label="Investment horizon" value={years} onChange={setYears} min={3} max={40} step={1} suffix=" yrs"/>
              <Slider label="Expected return" value={rate} onChange={setRate} min={6} max={18} step={0.5} suffix="% p.a."/>
              <Slider label="Annual step-up" value={stepUp} onChange={setStepUp} min={0} max={20} step={1} suffix="%"/>
            </div>

            <div style={{ marginTop: 28, paddingTop: 24, borderTop: "1px solid var(--hairline-light)" }}>
              <div className="eyebrow on-dark" style={{ marginBottom: 12 }}>Common goals</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {[
                  { l: "Retirement", m: 30000, y: 25, r: 12, s: 10 },
                  { l: "Child education", m: 15000, y: 15, r: 11, s: 8 },
                  { l: "FIRE @ 45", m: 75000, y: 18, r: 13, s: 12 },
                  { l: "First home", m: 40000, y: 7, r: 10, s: 5 },
                ].map(p => (
                  <button key={p.l} onClick={() => { setMonthly(p.m); setYears(p.y); setRate(p.r); setStepUp(p.s); }}
                    style={{ padding: "8px 14px", border: "1px solid var(--hairline-light)", borderRadius: 999, fontSize: 12, color: "var(--cream)", transition: "all .2s" }}
                    onMouseEnter={e => { e.currentTarget.style.background = "var(--gold-500)"; e.currentTarget.style.color = "var(--green-900)"; e.currentTarget.style.borderColor = "var(--gold-500)"; }}
                    onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--cream)"; e.currentTarget.style.borderColor = "var(--hairline-light)"; }}>
                    {p.l}
                  </button>
                ))}
              </div>
            </div>

            <a href="#consult" className="btn btn-cream" style={{ marginTop: 28, width: "100%", justifyContent: "center" }}>
              Build me a real plan <ArrowIcon/>
            </a>
            <p className="mono" style={{ fontSize: 10, color: "var(--green-300)", letterSpacing: "0.1em", marginTop: 14, lineHeight: 1.55 }}>
              ✱ Returns are illustrative. Past performance does not guarantee future results.
            </p>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px){
          .calc-grid{ grid-template-columns: 1fr !important; gap: 40px !important }
          .calc-panel{ position: static !important }
        }
        input[type=range]{ height: 6px; appearance: none; -webkit-appearance: none; border-radius: 999px; cursor: pointer }
        input[type=range]::-webkit-slider-thumb{ -webkit-appearance: none; width: 18px; height: 18px; background: var(--gold-500); border-radius: 50%; border: 3px solid var(--ink); cursor: pointer; box-shadow: 0 1px 4px rgba(0,0,0,0.4) }
        input[type=range]::-moz-range-thumb{ width: 18px; height: 18px; background: var(--gold-500); border-radius: 50%; border: 3px solid var(--ink); cursor: pointer }
        input[type=range]::-moz-range-progress{ background: var(--gold-500); height: 6px; border-radius: 999px }
      `}</style>
    </section>
  );
};

window.Calculator = Calculator;
