const DD_CATS = [["Financial Performance", "financial"], ["Brand Value", "brand"], ["Business Condition", "business"], ["Prospects for the Future", "prospects"], ["Customers", "customers"], ["Competitive Environment", "competitive"], ["Human Capital", "humanCapital"], ["Quality of Assets", "assets"], ["Structure of Purchase Transaction", "structure"], ["Other Risks", "otherRisks"]];
const DD_DOCS = [["Financial", "Current annual business plan"], ["Financial", "5 years of audited financial statements"], ["Financial", "3 years of federal and state tax returns"], ["Financial", "6 months of bank account history"], ["Insurance", "Liability insurance policy"], ["Insurance", "Workers compensation policy"], ["Insurance", "Life insurance on key personnel"], ["Insurance", "Health coverage documentation"], ["Insurance", "Documentation of recent claims"], ["Insurance", "Other insurance policies"], ["Legal", "Articles of incorporation"], ["Legal", "Amendments to articles"], ["Legal", "Bylaws"], ["Legal", "Office leases"], ["Legal", "Other facilities leases"], ["Legal", "Equipment leases"], ["IP", "Patents"], ["IP", "Trademarks"], ["IP", "Copyrights"], ["IP", "Trade secrets documentation"], ["Strategic", "Agreements with suppliers and vendors"], ["Strategic", "Selling agreements"], ["Strategic", "Special customer agreements"], ["Press", "Press releases — the company"], ["Press", "Press releases — competitors"], ["Press", "Press releases — suppliers"], ["Press", "Press releases — the industry"], ["Research", "Industry publications"], ["Research", "Research reports"], ["Research", "Web site references"], ["Research", "Consultant documentation"], ["Research", "Other research"], ["Other", "Available competitor information"], ["Other", "List of major customers"], ["Other", "List of major suppliers and vendors"], ["Other", "List of strategic partners and alliances"], ["Other", "Personal information for key employee background checks"], ["Other", "Signed permission forms for background/credit checks"]];

function DueDiligenceCalc() {
  const [max, setMax] = React.useState(5);
  const [sc, setSc] = React.useState({});
  const [ds, setDs] = React.useState(() => DD_DOCS.map(() => "no"));
  const card = React.useMemo(() => {
    const res = []; let tot = 0;
    for (const [name, key] of DD_CATS) { const s = sc[key]; if (!s || s < 1 || s > max) return null; tot += s; res.push({ name, score: s, pct: Math.round(s / max * 10000) / 100 }); }
    const mt = DD_CATS.length * max, op = tot / mt;
    const readiness = op >= .8 ? "Excellent — DD-ready for investor scrutiny" : op >= .6 ? "Good — minor gaps to address" : op >= .4 ? "Fair — significant preparation needed" : "Poor — major DD gaps, not investor-ready";
    return { res, tot, mt, op, pct: Math.round(op * 10000) / 100, readiness, weak: [...res].sort((a, b) => a.score - b.score).slice(0, 3), strong: [...res].sort((a, b) => b.score - a.score).slice(0, 3) };
  }, [sc, max]);
  const doc = React.useMemo(() => {
    const cs = {}; let rv = 0, mi = 0, na = 0; const miss = [];
    DD_DOCS.forEach(([c, it], i) => { cs[c] = cs[c] || { t: 0, r: 0, na: 0 }; cs[c].t++; const s = ds[i]; if (s === "yes") { rv++; cs[c].r++; } else if (s === "na") { na++; cs[c].na++; } else { mi++; miss.push([c, it]); } });
    const app = DD_DOCS.length - na, cp = app > 0 ? rv / app : 0;
    const readiness = cp >= .9 ? "Data room ready" : cp >= .7 ? "Mostly ready — fill remaining gaps" : cp >= .5 ? "Partially ready — significant gaps" : "Not ready — major documentation missing";
    return { rv, mi, na, cp, pct: Math.round(cp * 10000) / 100, readiness, cs, miss };
  }, [ds]);
  const setScale = m => { setMax(m); setSc(p => { const n = {}; for (const k in p) if (p[k] <= m) n[k] = p[k]; return n; }); };
  let lastCat = null;
  return (
    <div className="cx-stack">
      <div className="cx-split">
        <Box title="Assessment Scorecard" sub={`Rate each category from 1 (lowest) to ${max} (highest)`} right={<Seg value={max} set={setScale} options={[[5, "1-5 Scale"], [10, "1-10 Scale"]]} />}>
          <ul className="cx-list">{DD_CATS.map(([name, key]) => <li key={key}><span>{name}</span><Rate max={max} label={name} value={sc[key]} set={v => setSc(p => ({ ...p, [key]: v }))} /></li>)}</ul>
        </Box>
        <div className="cx-stick">
          <Box title="Scorecard Results" right={<PdfButton ready={!!card} />}>
            {!card ? <Empty>Enter valid scores (1-{max}) for all 10 categories to see results.</Empty> : <>
              <div className="cx-sum"><Gauge pct={card.op} label={card.pct + "%"} sub={`${card.tot} / ${card.mt}`} /><div className="t"><span className="cx-lb">Readiness</span><b>{card.readiness}</b></div></div>
              <div className="cx-mini"><span className="cx-lb">Category Breakdown</span>{card.res.map(c => <div key={c.name} className="row"><span>{c.name}</span><span className="tr"><i style={{ width: c.pct + "%" }}></i></span><b>{c.score}/{max}</b></div>)}</div>
              <Cells cols={2}>
                <div className="cx-res"><span className="cx-lb">Weakest Areas (Top 3)</span><div className="cx-tags">{card.weak.map(w => <span key={w.name} className="cx-tag r">{w.name}: {w.score}/{max}</span>)}</div></div>
                <div className="cx-res"><span className="cx-lb">Strongest Areas (Top 3)</span><div className="cx-tags">{card.strong.map(w => <span key={w.name} className="cx-tag g">{w.name}: {w.score}/{max}</span>)}</div></div>
              </Cells>
            </>}
          </Box>
        </div>
      </div>
      <div className="cx-split">
        <Box title="Document Checklist" sub="Mark each document as Have It, Missing, or N/A">
          <ul className="cx-list">{DD_DOCS.map(([c, it], i) => {
            const head = c !== lastCat; lastCat = c;
            return <React.Fragment key={i}>{head && <li className="grp">{c}</li>}<li><span>{it}</span><Tri label={it} value={ds[i]} set={v => setDs(p => p.map((x, j) => j === i ? v : x))} options={[["yes", "Yes", "g"], ["no", "No", "r"], ["na", "N/A", "n"]]} /></li></React.Fragment>;
          })}</ul>
        </Box>
        <div className="cx-stick">
          <Box title="Document Readiness Results">
            <div className="cx-sum"><Gauge pct={doc.cp} label={doc.pct + "%"} sub="Completion" /><div className="t"><span className="cx-lb">Document Readiness</span><b>{doc.readiness}</b></div></div>
            <Cells cols={3}><Res label="Documents Reviewed" value={`${doc.rv} / ${DD_DOCS.length}`} /><Res label="Missing Documents" value={String(doc.mi)} /><Res label="Not Applicable" value={String(doc.na)} /></Cells>
            <div className="cx-mini"><span className="cx-lb">Category Summary</span>{Object.entries(doc.cs).map(([c, d]) => <div key={c} className="row"><span>{c}</span><span className="tr"><i style={{ width: (d.t - d.na > 0 ? d.r / (d.t - d.na) * 100 : 0) + "%" }}></i></span><b>{d.r}/{d.t - d.na}{d.na > 0 ? ` (${d.na} N/A)` : ""}</b></div>)}</div>
            {doc.miss.length > 0 && <div className="cx-mini"><span className="cx-lb">Missing Documents</span><div className="cx-tags">{doc.miss.map(([c, it], i) => <span key={i} className="cx-tag r">[{c}] {it}</span>)}</div></div>}
          </Box>
        </div>
      </div>
    </div>
  );
}

mountCalc(
  <CalcPage slug="due-diligence-checker" title="Due Diligence" hl="Readiness Checker"
    lead={<><strong>Due diligence</strong> is the investor's deep-dive into your company before they write a check. Being prepared for DD dramatically increases your chances of closing a round quickly and on favorable terms. This tool helps you assess readiness across 10 key categories and track 38 essential documents.</>}
    how={<>
      <h2>Understanding Due Diligence Readiness</h2>
      <p><strong>Due diligence</strong> is the comprehensive investigation that investors conduct before finalizing an investment. It covers financial performance, legal standing, intellectual property, team quality, market position, and operational risks. Being well-prepared for DD can mean the difference between closing a round in weeks versus months — or losing the deal entirely.</p>
      <p><strong>The assessment scorecard</strong> evaluates 10 critical dimensions of your business: financial performance, brand value, business condition, future prospects, customers, competitive environment, human capital, asset quality, transaction structure, and other risks. Each category is scored on a 1-5 (or 1-10) scale, giving you a weighted overall readiness percentage.</p>
      <p><strong>The document checklist</strong> tracks 38 essential documents across 7 categories: financial records, insurance policies, legal documentation, intellectual property filings, strategic agreements, press and research materials, and other supporting documents. Having these documents organized in a virtual data room signals professionalism and preparedness to investors.</p>
      <p><strong>Best practices:</strong> Start preparing for due diligence well before you begin fundraising. Organize all documents in a secure virtual data room. Address the weakest areas identified by the scorecard first. Remember that investors view DD readiness as a proxy for how well you run your business — a disorganized DD process suggests a disorganized company.</p>
    </>}>
    <DueDiligenceCalc />
  </CalcPage>
);
