const NG_W = { Heaviest: 3, Heavy: 2, Moderate: 1 };
function ngFactors(t) {
  const inv = t === "vc" ? "VC" : "Angel", invs = t === "vc" ? "VCs" : "Angels";
  return [
    ["Do you have any Plan B Financiers (BATNA) / multiple simultaneous term sheets", "Heaviest", "BATNA"],
    ["Do you have a clearly defined path to a $1B-$10B Valuation", "Heaviest", "Vision"],
    ["Do you have proof of traction for Last 3 Months (are KPIs going up?)", "Heaviest", "Traction"],
    ["Have you maximized trust through transparency, open, authentic, collaborative interactions?", "Heaviest", "Trust"],
    ["Did you (privately) make an accurate assessment of your financial runway?", "Heaviest", "Runway"],
    ["Terms: valuation and dilution are critical, but are you emphasizing other critical deal terms?", "Heaviest", "Terms"],
    ["Terms: are you considering liquidation preference", "Heaviest", "Terms"],
    ["Terms: are you considering board control and voting rights", "Heaviest", "Terms"],
    ["Terms: founder vesting period", "Heaviest", "Terms"],
    ["Terms: right of first refusal", "Heaviest", "Terms"],
    ["Do you have an attorney &/or experienced founders as sounding boards during negotiation?", "Heavy", "Advisors"],
    [`Have you articulated to ${invs} your top 3 "wants"`, "Heavy", "Preparation"],
    ["Have you self-assessed your degree of emotional control during stressful situations?", "Heavy", "Self-Awareness"],
    ["Are you able to take a step back during an impasse to broaden your thinking?", "Heavy", "Flexibility"],
    [`Know thy investor: are you aware of your ${inv}'s average check size range?`, "Heavy", "Investor Intel"],
    [`Know thy investor: are ${inv}'s portfolio companies similar to yours?`, "Heavy", "Investor Intel"],
    [`Know thy investor: have you spoken to ${inv} references?`, "Heavy", "Investor Intel"],
    [`Know thy investor: have you asked the ${inv}'s their top 3 "wants"`, "Heavy", "Investor Intel"],
    [`Know thy investor: are you aware of your ${inv}'s average check size range? (confirm)`, "Heavy", "Investor Intel"],
    [`Know thy investor: do you know your ${inv}'s ownership stake target?`, "Heavy", "Investor Intel"],
    [`Did you allow ${inv} to send term sheet (not the other way around)?`, "Heavy", "Process"],
    ["Did you sketch out (privately) all of your potential dealbreakers?", "Heavy", "Preparation"],
    ["Are you clear that re-negotiating after a deal has been struck can be catastrophic?", "Heavy", "Discipline"],
    ["Is your negotiating style balanced or are you too aggressive or passive?", "Moderate", "Style"],
    [`Do you understand the current ${t === "vc" ? "VC" : "startup"} market and funding trends?`, "Moderate", "Market Intel"],
    ["Have you surmised the negotiating style of your investor?", "Moderate", "Investor Intel"],
    ["Have you dispensed with artificial FOMO?", "Moderate", "Discipline"],
    ["Have you sketched out the non-material negotiating terms?", "Moderate", "Preparation"],
    ["What social proof / social media footprint do you have?", "Moderate", "Social Proof"],
    ["What's the gravitas of your co-founders / advisors?", "Moderate", "Team"],
    ["Are you controlling the pace of the negotiation?", "Moderate", "Process"],
  ];
}

function NegotiationCalc() {
  const [v, setV] = React.useState("vc");
  const [sc, setSc] = React.useState(() => Array(31).fill(null));
  const F = React.useMemo(() => ngFactors(v), [v]);
  const done = sc.filter(x => x !== null).length;
  const r = React.useMemo(() => {
    if (sc.some(x => x === null)) return null;
    let ws = 0, mx = 0; const cat = {}, grp = { Heaviest: [], Heavy: [], Moderate: [] }, fr = [];
    F.forEach(([f, w, c], i) => { const s = sc[i], m = NG_W[w], x = s * m; ws += x; mx += 10 * m; cat[c] = cat[c] || { t: 0, m: 0, n: 0 }; cat[c].t += x; cat[c].m += 10 * m; cat[c].n++; grp[w].push(s); fr.push({ f, w, c, s }); });
    const op = ws / mx * 100, avg = {};
    for (const g in grp) avg[g] = Math.round(grp[g].reduce((a, b) => a + b, 0) / grp[g].length * 100) / 100;
    const sorted = [...fr].sort((a, b) => a.s !== b.s ? a.s - b.s : NG_W[b.w] - NG_W[a.w]);
    const assess = op >= 80 ? "Strong leverage — negotiate from strength" : op >= 60 ? "Moderate leverage — some gaps to shore up" : op >= 40 ? "Weak leverage — significant preparation needed" : "Very weak — delay negotiation until leverage improves";
    return { ws, mx, op: Math.round(op * 100) / 100, assess, avg, cat, weak: sorted.slice(0, 5), strong: sorted.slice(-5).reverse() };
  }, [sc, F]);
  let last = null;
  return (
    <div className="cx-split">
      <Box title="Factor Scores (0-10)" sub="Score each factor from 0 (not at all) to 10 (outstanding). Factors are weighted as Heaviest (3x), Heavy (2x), or Moderate (1x)." right={<Seg value={v} set={setV} options={[["vc", "VC Negotiation"], ["angel", "Angel Negotiation"]]} />}>
        <ul className="cx-list">{F.map(([f, w, c], i) => {
          const head = w !== last; last = w;
          return <React.Fragment key={i}>{head && <li className="grp">{w} Weight ({NG_W[w]}x multiplier) — {F.filter(x => x[1] === w).length} factors</li>}<li className="q"><div><p>{f}</p><small>{c}</small></div><Rate min={0} max={10} label={f} value={sc[i]} set={n => setSc(p => p.map((x, j) => j === i ? n : x))} /></li></React.Fragment>;
        })}</ul>
      </Box>
      <div className="cx-stick">
        <Box title="Results" right={<PdfButton ready={!!r} />}>
          {!r ? <Empty>Enter scores (0-10) for all 31 factors to see the calculated results. {done > 0 && <><br /><b style={{ color: "var(--accent-primary)" }}>{done} / 31 scored</b></>}</Empty> : <>
            <div className="cx-sum"><Gauge pct={r.op / 100} label={r.op + "%"} sub={`${r.ws} / ${r.mx}`} /><div className="t"><span className="cx-lb">Assessment</span><b>{r.assess}</b></div></div>
            <Cells cols={3}><Res label="Heaviest Avg (3x)" value={`${r.avg.Heaviest} / 10`} /><Res label="Heavy Avg (2x)" value={`${r.avg.Heavy} / 10`} /><Res label="Moderate Avg (1x)" value={`${r.avg.Moderate} / 10`} /></Cells>
            <div className="cx-mini"><span className="cx-lb">Category Breakdown</span>{Object.entries(r.cat).map(([c, d]) => { const p = Math.round(d.t / d.m * 10000) / 100; return <div key={c} className="row"><span>{c} ({d.n} factors)</span><span className="tr"><i style={{ width: p + "%" }}></i></span><b>{p}%</b></div>; })}</div>
            <div className="cx-mini"><span className="cx-lb">Weakest Factors (Top 5)</span><div className="ng-l r">{r.weak.map((f, i) => <div key={i}><b>{f.s}/10</b><span>{f.f} <small>[{f.w}]</small></span></div>)}</div></div>
            <div className="cx-mini"><span className="cx-lb">Strongest Factors (Top 5)</span><div className="ng-l g">{r.strong.map((f, i) => <div key={i}><b>{f.s}/10</b><span>{f.f} <small>[{f.w}]</small></span></div>)}</div></div>
          </>}
        </Box>
      </div>
    </div>
  );
}

mountCalc(
  <CalcPage slug="negotiation-leverage" title="Negotiation Leverage" hl="Self-Assessment"
    lead={<><strong>Leverage</strong> determines your negotiating power when closing a fundraise. This tool evaluates 31 weighted factors across BATNA, deal terms, traction, investor intel, and preparation — giving you a clear picture of where you stand before entering negotiations.</>}
    how={<>
      <h2>Understanding Negotiation Leverage</h2>
      <p><strong>Negotiation leverage</strong> is your ability to influence the outcome of fundraising negotiations in your favor. It comes from having alternatives (BATNA), strong traction, thorough preparation, deep investor knowledge, and disciplined execution during the negotiation process.</p>
      <p><strong>The weighting system</strong> reflects real-world impact on outcomes. "Heaviest" factors (3x weight) include your BATNA, traction proof, trust-building, runway assessment, and critical deal terms like liquidation preferences and board control. These are the factors that most dramatically affect your negotiating position.</p>
      <p><strong>"Heavy" factors (2x)</strong> include having legal counsel, articulating your priorities, emotional control, knowing your investor's check size and portfolio, and process discipline. These significantly affect outcomes but are more controllable through preparation.</p>
      <p><strong>"Moderate" factors (1x)</strong> include negotiating style, market awareness, social proof, team gravitas, and pace control. While important, these have less direct impact on the final terms compared to heaviest and heavy factors.</p>
      <p><strong>VC vs. Angel:</strong> The assessment structure is identical for both investor types, but the language adapts to the specific dynamics of VC negotiations versus Angel/HNW individual negotiations. Choose the variant that matches your current fundraising target.</p>
    </>}>
    <NegotiationCalc />
  </CalcPage>
);
