// Transaction Advisory · Page 6 — Deal Proposal
// A one-page confidential deal summary. Numbers are real (LTM revenue, adjusted
// EBITDA, implied multiple, asking-price range from the valuation math). The
// thesis + highlights are generated from data templates and are fully editable.
// "Print" produces a clean one-pager via window.print().
const { useState: useDP_useState, useEffect: useDP_useEffect } = React;

function DealProposalPage({ data, companyProfile, scopedCompanyId, setPage }) {
  const TA = window.TA;
  const m = TA.derive(data, companyProfile);
  if (!m.connected) return <TA.NotConnected what="The deal summary is built from your real revenue, EBITDA and valuation." />;

  const addbacks = TA.loadAddbacks(scopedCompanyId);
  const addbackTotal = addbacks.reduce((s, a) => s + (Number(a.amount) || 0), 0);
  const adjEbitda = (m.ltmEbitda || 0) + addbackTotal;
  const comp = TA.INDUSTRY_COMPS[TA.matchComp(m)];
  const dcfEv = window.computeDcfEV ? window.computeDcfEV(m, TA.loadDcf(scopedCompanyId)) : 0;

  // Asking-price range = blend of EBITDA-multiple low/high and DCF band, same as Valuation page.
  const lowV = (adjEbitda * comp.ebitda[0] + dcfEv * 0.85) / 2;
  const highV = (adjEbitda * comp.ebitda[1] + dcfEv * 1.15) / 2;
  const midV = (lowV + highV) / 2;
  const impliedMult = adjEbitda > 0 ? midV / adjEbitda : null;

  const key = "perdura_deal_" + (scopedCompanyId || "default");
  const [copy, setCopy] = useDP_useState(() => {
    try { const r = localStorage.getItem(key); if (r) return JSON.parse(r); } catch (e) { /* ignore */ }
    return generateDeal(m, TA);
  });
  useDP_useEffect(() => { try { localStorage.setItem(key, JSON.stringify(copy)); } catch (e) { /* ignore */ } }, [copy]);
  const regenerate = () => setCopy(generateDeal(m, TA));

  const money = (v) => TA.money(v, { compact: false });
  const contactName = (companyProfile && (companyProfile.owner_name || companyProfile.name)) || "—";
  const contactEmail = (companyProfile && companyProfile.owner_email) || (window.PerduraSession && window.PerduraSession.email) || "—";

  return (
    <div>
      <DealPrintStyle />
      <TA.Page title="Deal Proposal" badge="Transaction Advisory"
        subtitle="A one-page confidential deal summary — the first thing a buyer sees."
        actions={<>
          <button style={TA.tealBtn()} onClick={regenerate}>Generate</button>
          <button style={TA.ghostBtn()} onClick={() => window.print()}>Print</button>
        </>}>
        <div className="deal-doc" style={{ background: "var(--bg-card)", border: "1px solid var(--border)", borderRadius: 12, padding: "28px 32px", maxWidth: 760, margin: "0 auto" }}>
          <div style={{ textAlign: "center", borderBottom: "2px solid var(--text)", paddingBottom: 14, marginBottom: 18 }}>
            <div style={{ fontSize: 22, fontWeight: 800, color: "var(--text)", letterSpacing: "-0.02em" }}>{m.companyName}</div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.14em", color: "var(--text-3)", marginTop: 4 }}>CONFIDENTIAL DEAL SUMMARY</div>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "10px 24px", marginBottom: 20 }}>
            <Metric k="Asking price" v={`${TA.money(lowV, { compact: true })} – ${TA.money(highV, { compact: true })}`} accent />
            <Metric k="Revenue (LTM)" v={money(m.ltmRevenue)} />
            <Metric k="EBITDA (adjusted)" v={money(adjEbitda)} />
            <Metric k="Multiple" v={impliedMult != null ? impliedMult.toFixed(1) + "x" : "—"} />
          </div>

          <Block title="Why now / investment thesis">
            <textarea className="deal-edit" value={copy.thesis} onChange={e => setCopy(c => ({ ...c, thesis: e.target.value }))} style={ta()} />
            <div className="deal-print-only" style={{ display: "none", whiteSpace: "pre-wrap" }}>{copy.thesis}</div>
          </Block>

          <Block title="Key highlights">
            <textarea className="deal-edit" value={copy.highlights} onChange={e => setCopy(c => ({ ...c, highlights: e.target.value }))} style={ta({ minHeight: 110 })} />
            <div className="deal-print-only" style={{ display: "none", whiteSpace: "pre-wrap" }}>{copy.highlights}</div>
          </Block>

          <Block title="Financial snapshot">
            <SnapshotTable m={m} TA={TA} />
          </Block>

          <Block title="Next steps">
            <div style={{ fontSize: 13, color: "var(--text)", lineHeight: 1.6 }}>
              Interested parties should contact:<br />
              <strong>{contactName}</strong>{contactEmail !== "—" ? <> · {contactEmail}</> : null}
            </div>
          </Block>
        </div>
      </TA.Page>
    </div>
  );
}

function generateDeal(m, TA) {
  const money = (v) => TA.money(v, { compact: true });
  const sector = TA.matchComp(m);
  const growth = m.revenueGrowthPct != null ? TA.pct(m.revenueGrowthPct) : "stable";
  return {
    thesis: `${m.companyName} is a profitable ${sector.toLowerCase()} business generating ${money(m.ltmRevenue)} in revenue and ${money(m.ltmEbitda)} of EBITDA. With ${growth} year-over-year growth and clean, mapped financials, it presents a rare opportunity to acquire an established platform with clear operating leverage and expansion runway.`,
    highlights: [
      `• ${money(m.ltmRevenue)} LTM revenue at a ${m.ebitdaMargin != null ? TA.pct(m.ebitdaMargin) : "healthy"} EBITDA margin`,
      `• ${growth} revenue growth year-over-year`,
      m.topCustomerPct != null ? `• Largest customer only ${TA.pct(m.topCustomerPct)} of revenue` : "• Diversified customer base",
      `• ${m.yearsOfData != null ? m.yearsOfData.toFixed(1) : "Multiple"} years of clean financial history`,
    ].join("\n"),
  };
}

function SnapshotTable({ m, TA }) {
  const money = (v) => TA.money(v, { compact: true });
  const years = m.revAnnual || [], eb = m.ebitdaAnnual || [];
  const labels = years.map((_, i) => i === years.length - 1 ? "LTM" : "FY-" + (years.length - 1 - i));
  return (
    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
      <thead><tr style={{ color: "var(--text-3)", fontSize: 11 }}>
        <th style={{ textAlign: "left", padding: "4px 6px" }}></th>
        {labels.map((l, i) => <th key={i} style={{ textAlign: "right", padding: "4px 6px" }}>{l}</th>)}
      </tr></thead>
      <tbody>
        <tr style={{ borderTop: "1px solid var(--border)" }}><td style={{ padding: "5px 6px", fontWeight: 600 }}>Revenue</td>
          {years.map((y, i) => <td key={i} style={{ padding: "5px 6px", textAlign: "right", fontFamily: "ui-monospace,monospace" }}>{money(y.sum)}</td>)}</tr>
        <tr style={{ borderTop: "1px solid var(--border)" }}><td style={{ padding: "5px 6px", fontWeight: 600 }}>EBITDA</td>
          {eb.map((y, i) => <td key={i} style={{ padding: "5px 6px", textAlign: "right", fontFamily: "ui-monospace,monospace" }}>{money(y.sum)}</td>)}</tr>
      </tbody>
    </table>
  );
}

function Metric({ k, v, accent }) {
  return (
    <div>
      <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: "0.08em", color: "var(--text-3)", textTransform: "uppercase" }}>{k}</div>
      <div style={{ fontSize: 17, fontWeight: 800, color: accent ? "#0d9488" : "var(--text)", fontFamily: "ui-monospace,monospace", marginTop: 2 }}>{v}</div>
    </div>
  );
}
function Block({ title, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", color: "var(--text-3)", textTransform: "uppercase", marginBottom: 6 }}>{title}</div>
      {children}
    </div>
  );
}
function ta(extra) {
  return { width: "100%", minHeight: 72, resize: "vertical", padding: 10, border: "1px solid var(--border)", borderRadius: 8, background: "var(--bg-card)", color: "var(--text)", fontSize: 13, lineHeight: 1.6, fontFamily: "inherit", ...(extra || {}) };
}
function DealPrintStyle() {
  return (
    <style>{`
      @media print {
        body * { visibility: hidden; }
        .deal-doc, .deal-doc * { visibility: visible; }
        .deal-doc { position: absolute; left: 0; top: 0; width: 100%; border: none !important; box-shadow: none !important; }
        .deal-edit { display: none !important; }
        .deal-print-only { display: block !important; font-size: 13px; line-height: 1.6; }
      }
    `}</style>
  );
}

Object.assign(window, { DealProposalPage });
