// Interactive simulation — runway sliders + risk diagnosis dashboard

const fmtMoney = (n) => {
  if (n >= 1e6) return '$' + (n / 1e6).toFixed(2) + 'M';
  if (n >= 1e3) return '$' + Math.round(n / 1e3) + 'k';
  return '$' + n.toLocaleString();
};

const Slider = ({ label, value, min, max, step, onChange, fmt }) =>
<div>
    <div className="slider-row">
      <span className="label">{label}</span>
      <span className="value">{fmt ? fmt(value) : value}</span>
    </div>
    <input type="range" min={min} max={max} step={step}
  value={value} onChange={(e) => onChange(parseFloat(e.target.value))} />
  </div>;


const Simulator = () => {
  const Ic = window.Ic;
  const [cash, setCash] = React.useState(780000);
  const [burn, setBurn] = React.useState(184000);
  const [fixed, setFixed] = React.useState(46000);
  const [payroll, setPayroll] = React.useState(112000);
  const [liab, setLiab] = React.useState(52000);
  const [closeCost, setCloseCost] = React.useState(82000);

  const runway = Math.max(0.1, cash / burn);
  const downsizedBurn = burn * 0.62;
  const downsizedRunway = cash / downsizedBurn;
  const minCashForClosure = closeCost + liab * 0.6;
  const monthsRemaining = runway;

  // cash-out date
  const dt = new Date(2026, 4, 3); // May 3 2026
  dt.setDate(dt.getDate() + Math.round(runway * 30));
  const cashOutStr = dt.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });

  let verdict = "Prepare for closure — start within 30 days.";
  let verdictBody = "Operating one more month risks falling below the minimum cash you'd need to close safely.";
  let kind = 'warn';
  if (cash > burn * 5 && minCashForClosure < cash * 0.4) {
    verdict = "Continue or downsize — closure is not yet forced.";
    verdictBody = "You have meaningful runway above the minimum closure-prep reserve.";
    kind = 'go';
  } else if (cash < minCashForClosure * 1.1) {
    verdict = "Expert intervention may be needed.";
    verdictBody = "Cash is approaching the minimum required for safe closure prep — review with an attorney.";
    kind = 'crit';
  }

  return (
    <section id="simulate">
      <div className="wrap">
        <div className="sec-head-center">
          <div className="sec-eyebrow">Interactive simulation</div>
          <h2 className="sec-title">Simulate your runway, risks,<br />and next best move.</h2>
          <p className="sec-sub">Move the sliders. Watch the numbers — and the recommended path — change in real time.</p>
        </div>

        <div className="sim-grid">
          {/* Part A — Runway */}
          <div className="sim-card">
            <div className="sim-card-head">
              <h4><Ic.hourglass /> &nbsp;Part A · Runway &amp; timing simulator</h4>
              <span className="tag">Live</span>
            </div>
            <div className="sim-body">
              <p style={{ margin: '0 0 18px', fontSize: 13.5, color: 'var(--muted)', lineHeight: 1.5 }}>
                <strong style={{ color: 'var(--ink-2)' }}>Should I shut down now, keep operating for one more month, or downsize?</strong>
              </p>

              <Slider label="Current cash balance" value={cash} min={50000} max={3000000} step={5000} onChange={setCash} fmt={fmtMoney} />
              <Slider label="Monthly burn rate" value={burn} min={20000} max={500000} step={1000} onChange={setBurn} fmt={fmtMoney} />
              <Slider label="Fixed costs" value={fixed} min={5000} max={150000} step={500} onChange={setFixed} fmt={fmtMoney} />
              <Slider label="Payroll expenses" value={payroll} min={0} max={300000} step={1000} onChange={setPayroll} fmt={fmtMoney} />
              <Slider label="Outstanding liabilities" value={liab} min={0} max={400000} step={1000} onChange={setLiab} fmt={fmtMoney} />
              <Slider label="Estimated closure cost" value={closeCost} min={20000} max={250000} step={1000} onChange={setCloseCost} fmt={fmtMoney} />

              <div className="sim-output" style={{ marginTop: 14 }}>
                <div className="out hi">
                  <div className="lbl">Current runway</div>
                  <div className="v">{runway.toFixed(1)}<small>months</small></div>
                </div>
                <div className="out">
                  <div className="lbl">Expected cash-out</div>
                  <div className="v" style={{ fontSize: 20 }}>{cashOutStr}</div>
                </div>
                <div className="out">
                  <div className="lbl">Cost of one more month</div>
                  <div className="v">{fmtMoney(burn)}</div>
                </div>
                <div className="out">
                  <div className="lbl">Min. cash for closure prep</div>
                  <div className="v">{fmtMoney(Math.round(minCashForClosure))}</div>
                </div>
                <div className="out">
                  <div className="lbl">Survival under downsize</div>
                  <div className="v">{downsizedRunway.toFixed(1)}<small>mo</small></div>
                </div>
                <div className="out">
                  <div className="lbl">Suggested timing range</div>
                  <div className="v" style={{ fontSize: 18 }}>{Math.max(1, Math.round(monthsRemaining - 2))}–{Math.round(monthsRemaining)} mo</div>
                </div>
              </div>

              <div className="verdict" style={{
                background: kind === 'go' ? '#1e5b3e' : kind === 'crit' ? '#5b1e1e' : 'var(--ink)'
              }}>
                <div className="ico">
                  {kind === 'go' ? <Ic.check /> : <Ic.alert />}
                </div>
                <div>
                  <h5>{verdict}</h5>
                  <p>{verdictBody}</p>
                </div>
              </div>
            </div>
          </div>

          {/* Part B — Risk Diagnosis */}
          <RiskDiagnosis />
        </div>
      </div>
    </section>);

};

const RiskDiagnosis = () => {
  const Ic = window.Ic;
  const [progress, setProgress] = React.useState(2);
  React.useEffect(() => {
    const i = setInterval(() => setProgress((p) => p >= 4 ? 2 : p + 1), 2200);
    return () => clearInterval(i);
  }, []);

  const risks = [
  { area: 'Accounting', ico: <Ic.chart />, status: 'review', title: 'Unpaid invoices detected', meta: '$24,800 across 3 vendors', dot: 'amber' },
  { area: 'Tax', ico: <Ic.scale />, status: 'high', title: 'Possible payroll tax issue', meta: 'Q1 federal deposit may be late', dot: 'red' },
  { area: 'Payroll', ico: <Ic.users />, status: 'high', title: 'Final paycheck rule may apply', meta: 'CA: same-day on termination', dot: 'red' },
  { area: 'Legal', ico: <Ic.doc />, status: 'review', title: 'Contract termination clause', meta: '2 SaaS, 12-mo notice obligation', dot: 'amber' },
  { area: 'Cap table', ico: <Ic.briefcase />, status: 'expert', title: 'Investor consent required', meta: 'Series Seed protective provisions', dot: 'red' },
  { area: 'State', ico: <Ic.globe />, status: 'review', title: 'Foreign registration withdrawal', meta: 'CA SOS + FTB tax clearance', dot: 'amber' }];

  const map = { low: { cls: 'green', txt: 'Low risk' }, review: { cls: 'amber', txt: 'Needs review' }, high: { cls: 'red', txt: 'High priority' }, expert: { cls: 'blue', txt: 'Expert review' } };

  const trackerSteps = ['Data connected', 'Risks detected', 'Options simulated', 'Report generated'];

  return (
    <div className="sim-card">
      <div className="sim-card-head">
        <h4><Ic.shield /> &nbsp;Part B · Risk diagnosis engine</h4>
        <span className="tag"><span className="live-dot"></span>Scanning</span>
      </div>
      <div className="risk-tracker">
        {trackerSteps.map((s, i) =>
        <React.Fragment key={s}>
            <div className={`step-mini ${i < progress ? 'done' : ''} ${i === progress ? 'active' : ''}`}>
              <span className="b">{i < progress && <Ic.check />}</span>
              <span style={{ color: i <= progress ? 'var(--ink-2)' : 'var(--muted-2)' }}>{s}</span>
            </div>
            {i < trackerSteps.length - 1 && <span className="arr">›</span>}
          </React.Fragment>
        )}
      </div>
      <div className="risk-grid">
        {risks.map((r, i) =>
        <div className="risk-card" key={i}>
            <div className="top">
              <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--muted)' }}>
                <span style={{ width: 18, height: 18, display: 'grid', placeItems: 'center', borderRadius: 5, background: '#fff', color: 'var(--ink-2)' }}>{r.ico}</span>
                {r.area}
              </span>
              <span className={`badge ${map[r.status].cls}`}>{map[r.status].txt}</span>
            </div>
            <div className="name" style={{ fontSize: 13, fontWeight: 500, marginBottom: 3 }}>{r.title}</div>
            <div className="body">{r.meta}</div>
          </div>
        )}
      </div>
      <div style={{ padding: '0 18px 18px' }}>
        <div style={{
          padding: '14px 16px', borderRadius: 12,
          background: 'var(--lavender)', border: '1px solid rgba(122,118,214,.2)',
          fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5, backgroundColor: "rgb(245, 215, 207)"
        }}>
          <strong>Summary —</strong> 2 high-priority items, 3 needing review, 1 requiring expert input. Bring this list to your attorney before scheduling final filings.
        </div>
      </div>
    </div>);

};

window.Simulator = Simulator;