// Transaction Advisory · Page 2 — Valuation Model
// Revenue-multiple, EBITDA-multiple and DCF methodologies side by side. All base
// figures (LTM revenue, LTM/adjusted EBITDA) come from real GL data; the CFO
// tunes the multiples with sliders. The DCF value is read from the saved DCF model.
const { useState: useVAL_useState, useMemo: useVAL_useMemo } = React;

function ValuationPage({ data, companyProfile, scopedCompanyId, setPage }) {
  const TA = window.TA;
  const m = TA.derive(data, companyProfile);
  if (!m.connected) return <TA.NotConnected what="The valuation model multiplies your real LTM revenue and EBITDA against market comps." />;

  const compKey = TA.matchComp(m);
  const comp = TA.INDUSTRY_COMPS[compKey];

  // Adjusted EBITDA = LTM EBITDA + saved normalizing add-backs (EBITDA page).
  const addbacks = TA.loadAddbacks(scopedCompanyId);
  const addbackTotal = addbacks.reduce((s, a) => s + (Number(a.amount) || 0), 0);
  const adjEbitda = (m.ltmEbitda || 0) + addbackTotal;

  const [revMult, setRevMult] = useVAL_useState(+(((comp.rev[0] + comp.rev[1]) / 2)).toFixed(1));
  const [ebitdaMult, setEbitdaMult] = useVAL_useState(+(((comp.ebitda[0] + comp.ebitda[1]) / 2)).toFixed(1));

  const revValue = (m.ltmRevenue || 0) * revMult;
  const ebitdaValue = adjEbitda * ebitdaMult;

  // DCF enterprise value from the saved assumptions (mirrors the DCF page math).
  const dcfValue = useVAL_useMemo(() => computeDcfEV(m, TA.loadDcf(scopedCompanyId)), [m.ltmRevenue, m.ltmEbitda, scopedCompanyId]);

  const money = (v) => TA.money(v, { compact: false });
  const rows = [
    { label: "Revenue Multiple", low: (m.ltmRevenue || 0) * comp.rev[0], mid: revValue, high: (m.ltmRevenue || 0) * comp.rev[1] },
    { label: "EBITDA Multiple", low: adjEbitda * comp.ebitda[0], mid: ebitdaValue, high: adjEbitda * comp.ebitda[1] },
    { label: "DCF", low: dcfValue * 0.85, mid: dcfValue, high: dcfValue * 1.15 },
  ];
  const blended = {
    low: rows.reduce((s, r) => s + r.low, 0) / rows.length,
    mid: rows.reduce((s, r) => s + r.mid, 0) / rows.length,
    high: rows.reduce((s, r) => s + r.high, 0) / rows.length,
  };

  const compTable = (kind) => (
    <div style={{ marginTop: 10, fontSize: 12, color: "var(--text-3)" }}>
      <div style={{ fontWeight: 700, color: "var(--text)", marginBottom: 4 }}>Industry comparable ranges ({kind})</div>
      {Object.entries(TA.INDUSTRY_COMPS).map(([k, v]) => (
        <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "2px 0", fontWeight: k === compKey ? 700 : 400, color: k === compKey ? "var(--text)" : "var(--text-3)" }}>
          <span>{k}{k === compKey ? "  ◄ your sector" : ""}</span>
          <span>{v[kind][0]}x – {v[kind][1]}x {kind}</span>
        </div>
      ))}
    </div>
  );

  return (
    <TA.Page title="Valuation Model" badge="Transaction Advisory"
      subtitle="Indicative valuation across three methodologies. Drag the multiples to test scenarios.">
      <TA.Card title="Indicative valuation range">
        <TA.RangeBar low={blended.low} mid={blended.mid} high={blended.high} />
      </TA.Card>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginTop: 18 }}>
        <TA.Card title="Method 1 · Revenue multiple">
          <KV k="LTM Revenue" v={money(m.ltmRevenue)} />
          <div style={{ margin: "10px 0" }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 4 }}>
              <span style={{ color: "var(--text-3)" }}>Revenue multiple</span>
              <span style={{ fontWeight: 800, color: "var(--text)" }}>{revMult.toFixed(1)}x</span>
            </div>
            <TA.Slider value={revMult} min={0.5} max={10} step={0.1} onChange={setRevMult} format={x => x + "x"} />
          </div>
          <KV k="Indicated value" v={money(revValue)} bold />
          {compTable("rev")}
        </TA.Card>

        <TA.Card title="Method 2 · EBITDA multiple">
          <KV k="LTM EBITDA" v={money(m.ltmEbitda)} />
          <KV k="Adjusted EBITDA" v={money(adjEbitda)} sub={addbackTotal ? `incl. ${money(addbackTotal)} add-backs` : "no add-backs yet"} />
          <div style={{ margin: "10px 0" }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 4 }}>
              <span style={{ color: "var(--text-3)" }}>EBITDA multiple</span>
              <span style={{ fontWeight: 800, color: "var(--text)" }}>{ebitdaMult.toFixed(1)}x</span>
            </div>
            <TA.Slider value={ebitdaMult} min={3} max={15} step={0.1} onChange={setEbitdaMult} format={x => x + "x"} />
          </div>
          <KV k="Indicated value" v={money(ebitdaValue)} bold />
          {compTable("ebitda")}
        </TA.Card>
      </div>

      <div style={{ marginTop: 18 }}>
        <TA.Card title="Method 3 · Discounted cash flow" right={<button style={TA.ghostBtn()} onClick={() => setPage && setPage("dcf_model")}>View DCF Model →</button>}>
          <KV k="DCF indicated value" v={money(dcfValue)} bold />
        </TA.Card>
      </div>

      <div style={{ marginTop: 18 }}>
        <TA.Card title="Valuation summary">
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
            <thead>
              <tr style={{ color: "var(--text-3)", fontSize: 11.5, textTransform: "uppercase", letterSpacing: "0.04em" }}>
                <th style={{ textAlign: "left", padding: "6px 8px" }}>Method</th>
                <th style={{ textAlign: "right", padding: "6px 8px" }}>Low</th>
                <th style={{ textAlign: "right", padding: "6px 8px" }}>Mid</th>
                <th style={{ textAlign: "right", padding: "6px 8px" }}>High</th>
              </tr>
            </thead>
            <tbody>
              {rows.map(r => (
                <tr key={r.label} style={{ borderTop: "1px solid var(--border)" }}>
                  <td style={{ padding: "8px", fontWeight: 600, color: "var(--text)" }}>{r.label}</td>
                  <td style={{ padding: "8px", textAlign: "right", fontFamily: "ui-monospace,monospace" }}>{money(r.low)}</td>
                  <td style={{ padding: "8px", textAlign: "right", fontFamily: "ui-monospace,monospace" }}>{money(r.mid)}</td>
                  <td style={{ padding: "8px", textAlign: "right", fontFamily: "ui-monospace,monospace" }}>{money(r.high)}</td>
                </tr>
              ))}
              <tr style={{ borderTop: "2px solid var(--border-strong,var(--border))", fontWeight: 800 }}>
                <td style={{ padding: "10px 8px", color: "var(--text)" }}>Blended range</td>
                <td style={{ padding: "10px 8px", textAlign: "right", fontFamily: "ui-monospace,monospace" }}>{money(blended.low)}</td>
                <td style={{ padding: "10px 8px", textAlign: "right", fontFamily: "ui-monospace,monospace", color: "#0d9488" }}>{money(blended.mid)}</td>
                <td style={{ padding: "10px 8px", textAlign: "right", fontFamily: "ui-monospace,monospace" }}>{money(blended.high)}</td>
              </tr>
            </tbody>
          </table>
        </TA.Card>
      </div>
    </TA.Page>
  );
}

function KV({ k, v, sub, bold }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "5px 0" }}>
      <span style={{ fontSize: 13, color: "var(--text-3)" }}>{k}{sub && <span style={{ fontSize: 11, marginLeft: 6, color: "var(--text-3)" }}>({sub})</span>}</span>
      <span style={{ fontSize: bold ? 16 : 14, fontWeight: bold ? 800 : 600, color: bold ? "#0d9488" : "var(--text)", fontFamily: "ui-monospace,monospace" }}>{v}</span>
    </div>
  );
}

// Shared DCF enterprise-value math (kept in sync with pages-dcf.jsx).
function computeDcfEV(m, a) {
  if (!m || !m.ltmRevenue) return 0;
  let rev = m.ltmRevenue;
  const disc = [], fcfs = [];
  for (let y = 1; y <= 5; y++) {
    const g = y <= 3 ? a.growth13 : a.growth45;
    rev = rev * (1 + g);
    const ebitda = rev * a.ebitdaMargin;
    const da = rev * a.daPct;
    const ebit = ebitda - da;
    const tax = Math.max(0, ebit) * a.taxRate;
    const nopat = ebit - tax;
    const capex = rev * a.capexPct;
    const wc = rev * a.wcPct;
    const fcf = nopat + da - capex - wc;
    const df = 1 / Math.pow(1 + a.wacc, y);
    fcfs.push(fcf * df);
    disc.push(df);
  }
  const sumPv = fcfs.reduce((s, v) => s + v, 0);
  const lastFcf = fcfs.length ? fcfs[fcfs.length - 1] / disc[disc.length - 1] : 0;
  const tv = a.wacc > a.terminalGrowth ? (lastFcf * (1 + a.terminalGrowth)) / (a.wacc - a.terminalGrowth) : 0;
  const pvTv = tv * disc[disc.length - 1];
  return sumPv + pvTv;
}

Object.assign(window, { ValuationPage, computeDcfEV });
