// Transaction Advisory · Page 1 — M&A Readiness
// A scored, go-to-market readiness assessment built from real GL data. Checks
// that cannot be sourced from the live ledger (recurring-revenue %) resolve to a
// neutral "needs data" state rather than a fabricated pass/fail.
const { useState: useMAR_useState } = React;

function MAReadinessPage({ data, companyProfile, scopedCompanyId, setPage }) {
  const TA = window.TA;
  const m = TA.derive(data, companyProfile);
  if (!m.connected) return <TA.NotConnected what="M&A readiness scores your books against buyer diligence standards." />;

  // Each check: pass / fail / unknown (null input). Weight only counts on a pass.
  const CHECKS = [
    { id: "financials_3yr", label: "3 years of clean financials", weight: 20,
      value: m.yearsOfData, ok: m.yearsOfData != null ? m.yearsOfData >= 3 : null,
      detail: m.yearsOfData != null ? `${m.yearsOfData.toFixed(1)} years of GL history` : null,
      fix: "Import or reconcile at least 3 full years of history.", eta: "1–2 weeks", impact: "Unlocks buyer confidence; removes a common price chip." },
    { id: "revenue_growth", label: "Positive revenue trend", weight: 15,
      value: m.revenueGrowthPct, ok: m.revenueGrowthPct != null ? m.revenueGrowthPct > 0 : null,
      detail: m.revenueGrowthPct != null ? `YoY revenue ${TA.pct(m.revenueGrowthPct)}` : null,
      fix: "Stabilise or grow top-line before going to market.", eta: "1–2 quarters", impact: "Declining revenue compresses the multiple." },
    { id: "positive_ebitda", label: "Positive EBITDA", weight: 20,
      value: m.ltmEbitda, ok: m.ltmEbitda != null ? m.ltmEbitda > 0 : null,
      detail: m.ltmEbitda != null ? `LTM EBITDA ${TA.money(m.ltmEbitda, { compact: true })}` : null,
      fix: "Improve margins or normalise add-backs (see EBITDA Analysis).", eta: "1–2 quarters", impact: "Most SMBs trade on an EBITDA multiple — this is the base." },
    { id: "customer_diversity", label: "No single customer > 25% of revenue", weight: 15,
      value: m.topCustomerPct, ok: m.topCustomerPct != null ? m.topCustomerPct < 0.25 : null,
      detail: m.topCustomerPct != null ? `Top customer is ${TA.pct(m.topCustomerPct)}${m.topCustomerName ? " (" + m.topCustomerName + ")" : ""}` : null,
      fix: "Diversify revenue; reduce reliance on the largest account.", eta: "2–4 quarters", impact: "Concentration risk is a top diligence red flag." },
    { id: "recurring_revenue", label: "Recurring or contracted revenue", weight: 10,
      value: m.recurringRevenuePct, ok: m.recurringRevenuePct != null ? m.recurringRevenuePct > 0.3 : null,
      detail: m.recurringRevenuePct != null ? `${TA.pct(m.recurringRevenuePct)} recurring` : null,
      fix: "Tag recurring/contracted revenue in your ledger to evidence it.", eta: "Data setup", impact: "Recurring revenue commands materially higher multiples." },
    { id: "clean_books", label: "GL mapped and reconciled", weight: 10,
      value: m.mappingCoverage, ok: m.mappingCoverage != null ? m.mappingCoverage > 0.9 : null,
      detail: m.mappingCoverage != null ? `${TA.pct(m.mappingCoverage)} of transactions mapped` : null,
      fix: "Map remaining accounts (Admin → Category Mapping).", eta: "1 week", impact: "Clean books speed diligence and reduce escrow holdbacks." },
    { id: "growth_story", label: "YoY revenue growth > 10%", weight: 10,
      value: m.revenueGrowthPct, ok: m.revenueGrowthPct != null ? m.revenueGrowthPct > 0.10 : null,
      detail: m.revenueGrowthPct != null ? `Growth is ${TA.pct(m.revenueGrowthPct)}` : null,
      fix: "Build a credible growth story buyers can underwrite.", eta: "Ongoing", impact: "A double-digit growth story supports a premium multiple." },
  ];

  const score = CHECKS.reduce((s, c) => s + (c.ok === true ? c.weight : 0), 0);
  const failed = CHECKS.filter(c => c.ok !== true);
  const band = score >= 75 ? { t: "Market-ready", c: "#16a34a" } : score >= 50 ? { t: "Nearly ready", c: "#d97706" } : { t: "Preparation needed", c: "#dc2626" };

  const rowIcon = (ok) => ok === true ? "✅" : ok === false ? "❌" : "⚠️";

  return (
    <TA.Page title="M&A Readiness" badge="Transaction Advisory"
      subtitle="How ready your business is to go to market — scored against buyer diligence standards.">
      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 18, alignItems: "start" }}>
        <TA.Card style={{ textAlign: "center" }}>
          <TA.Gauge value={score} />
          <div style={{ fontSize: 14, fontWeight: 800, color: band.c, marginTop: 6 }}>{band.t}</div>
          <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 6, lineHeight: 1.5 }}>
            {CHECKS.filter(c => c.ok === true).length} of {CHECKS.length} checks passing
          </div>
        </TA.Card>

        <TA.Card title="Readiness checklist">
          <div>
            {CHECKS.map(c => (
              <div key={c.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderBottom: "1px solid var(--border)" }}>
                <span style={{ fontSize: 16, width: 22, textAlign: "center" }}>{rowIcon(c.ok)}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text)" }}>{c.label}</div>
                  {c.detail
                    ? <div style={{ fontSize: 11.5, color: c.ok === true ? "var(--text-3)" : band.c }}>{c.detail}{c.ok === false ? " — action needed" : ""}</div>
                    : <div style={{ fontSize: 11.5, color: "var(--text-3)", fontStyle: "italic" }}>Needs data to evaluate</div>}
                </div>
                <div style={{ fontSize: 13, fontWeight: 700, color: c.ok === true ? "#16a34a" : "var(--text-3)", width: 64, textAlign: "right" }}>
                  {c.ok === true ? `+${c.weight}` : "+0"} pts
                </div>
              </div>
            ))}
          </div>
        </TA.Card>
      </div>

      <div style={{ marginTop: 18 }}>
        <TA.Card title="CFO actions — fix before going to market">
          {failed.length === 0
            ? <div style={{ fontSize: 13.5, color: "#16a34a", fontWeight: 600 }}>✅ Every check is passing. Your books present as market-ready.</div>
            : (
              <div style={{ display: "grid", gap: 10 }}>
                {failed.map(c => (
                  <div key={c.id} style={{ display: "grid", gridTemplateColumns: "1fr 120px 1fr", gap: 12, padding: "10px 12px", background: "var(--bg-elev,rgba(0,0,0,0.02))", border: "1px solid var(--border)", borderRadius: 8 }}>
                    <div>
                      <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--text)" }}>{c.label}</div>
                      <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>{c.fix}</div>
                    </div>
                    <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>
                      <div style={{ fontWeight: 600, color: "var(--text)" }}>Est. time</div>{c.eta}
                    </div>
                    <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>
                      <div style={{ fontWeight: 600, color: "var(--text)" }}>Valuation impact</div>{c.impact}
                    </div>
                  </div>
                ))}
              </div>
            )}
          <div style={{ marginTop: 14, display: "flex", gap: 8 }}>
            <button style={TA.tealBtn()} onClick={() => setPage && setPage("valuation")}>See indicative valuation →</button>
            <button style={TA.ghostBtn()} onClick={() => setPage && setPage("ebitda_analysis")}>Review EBITDA add-backs</button>
          </div>
        </TA.Card>
      </div>
    </TA.Page>
  );
}

Object.assign(window, { MAReadinessPage });
