// Transaction Advisory · Page 4 — DCF Model
// A 5-year discounted cash flow built off the real LTM revenue base. All
// assumptions are editable and saved to localStorage (perdura_dcf_{companyId}).
// The enterprise-value math mirrors computeDcfEV() so the Valuation page agrees.
const { useState: useDCF_useState, useEffect: useDCF_useEffect, useMemo: useDCF_useMemo } = React;

function DcfModelPage({ data, companyProfile, scopedCompanyId, setPage }) {
  const TA = window.TA;
  const m = TA.derive(data, companyProfile);
  if (!m.connected) return <TA.NotConnected what="The DCF projects your real LTM revenue forward over five years." />;

  const [a, setA] = useDCF_useState(() => TA.loadDcf(scopedCompanyId));
  useDCF_useEffect(() => { TA.saveDcf(scopedCompanyId, a); }, [a]);
  const set = (k, v) => setA(prev => ({ ...prev, [k]: v }));

  const model = useDCF_useMemo(() => buildDcf(m.ltmRevenue, a), [m.ltmRevenue, a]);
  const money = (v) => TA.money(v, { compact: true });

  const ASSUMPTIONS = [
    { k: "growth13", label: "Revenue growth (Yr 1–3)", min: -0.1, max: 0.5, step: 0.01, pct: true },
    { k: "growth45", label: "Revenue growth (Yr 4–5)", min: -0.1, max: 0.4, step: 0.01, pct: true },
    { k: "ebitdaMargin", label: "EBITDA margin (stable)", min: 0.02, max: 0.6, step: 0.01, pct: true },
    { k: "daPct", label: "D&A as % of revenue", min: 0, max: 0.15, step: 0.005, pct: true },
    { k: "capexPct", label: "Capex as % of revenue", min: 0, max: 0.15, step: 0.005, pct: true },
    { k: "wcPct", label: "Working capital change", min: 0, max: 0.15, step: 0.005, pct: true },
    { k: "taxRate", label: "Tax rate", min: 0, max: 0.45, step: 0.01, pct: true },
    { k: "terminalGrowth", label: "Terminal growth rate", min: 0, max: 0.06, step: 0.005, pct: true },
    { k: "wacc", label: "Discount rate (WACC)", min: 0.05, max: 0.25, step: 0.005, pct: true },
  ];

  const ROWS = [
    { label: "Revenue", key: "revenue" },
    { label: "EBITDA", key: "ebitda" },
    { label: "Less: D&A", key: "da", neg: true, indent: true },
    { label: "EBIT", key: "ebit" },
    { label: "Less: Taxes", key: "tax", neg: true, indent: true },
    { label: "NOPAT", key: "nopat" },
    { label: "Add: D&A", key: "da2", indent: true },
    { label: "Less: Capex", key: "capex", neg: true, indent: true },
    { label: "Less: WC change", key: "wc", neg: true, indent: true },
    { label: "Free Cash Flow", key: "fcf", bold: true },
    { label: "Discount factor", key: "df", plain: true },
    { label: "PV of FCF", key: "pvfcf", bold: true },
  ];

  return (
    <TA.Page title="DCF Model" badge="Transaction Advisory"
      subtitle="A five-year discounted cash flow from your real LTM base. Every assumption is live.">
      <div style={{ display: "grid", gridTemplateColumns: "300px 1fr", gap: 18, alignItems: "start" }}>
        <TA.Card title="Assumptions">
          {ASSUMPTIONS.map(as => (
            <div key={as.k} style={{ marginBottom: 12 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 3 }}>
                <span style={{ color: "var(--text-3)" }}>{as.label}</span>
                <span style={{ fontWeight: 800, color: "var(--text)" }}>{(a[as.k] * 100).toFixed(as.step < 0.01 ? 1 : 0)}%</span>
              </div>
              <input type="range" min={as.min} max={as.max} step={as.step} value={a[as.k]}
                onChange={e => set(as.k, parseFloat(e.target.value))}
                style={{ width: "100%", accentColor: "var(--accent,#0F2044)" }} />
            </div>
          ))}
        </TA.Card>

        <div>
          <TA.Card title="5-year projection" style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5, minWidth: 640 }}>
              <thead>
                <tr style={{ color: "var(--text-3)", fontSize: 11 }}>
                  <th style={{ textAlign: "left", padding: "5px 8px" }}></th>
                  <th style={{ textAlign: "right", padding: "5px 8px" }}>LTM</th>
                  {[1, 2, 3, 4, 5].map(y => <th key={y} style={{ textAlign: "right", padding: "5px 8px" }}>Yr {y}</th>)}
                </tr>
              </thead>
              <tbody>
                {ROWS.map(r => (
                  <tr key={r.key} style={{ borderTop: r.bold ? "1px solid var(--border)" : "none" }}>
                    <td style={{ padding: "4px 8px", paddingLeft: r.indent ? 20 : 8, fontWeight: r.bold ? 700 : 500, color: "var(--text)" }}>{r.label}</td>
                    <td style={{ padding: "4px 8px", textAlign: "right", fontFamily: "ui-monospace,monospace", color: "var(--text-3)" }}>
                      {r.key === "revenue" ? money(m.ltmRevenue) : r.key === "ebitda" ? money(m.ltmEbitda) : ""}
                    </td>
                    {model.years.map((yr, i) => (
                      <td key={i} style={{ padding: "4px 8px", textAlign: "right", fontFamily: "ui-monospace,monospace", fontWeight: r.bold ? 700 : 400, color: r.bold ? "var(--text)" : "var(--text-3)" }}>
                        {r.plain ? yr[r.key].toFixed(2) : cell(yr[r.key], r.neg, money)}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </TA.Card>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginTop: 18 }}>
            <TA.Card title="Valuation output">
              <Out k="Sum of PV (FCF)" v={money(model.sumPv)} />
              <Out k="Terminal value" v={money(model.tv)} />
              <Out k="PV of terminal value" v={money(model.pvTv)} />
              <div style={{ borderTop: "1px solid var(--border-strong,var(--border))", margin: "8px 0" }} />
              <Out k="Enterprise value" v={money(model.ev)} bold />
            </TA.Card>

            <TA.Card title="Sensitivity — Enterprise Value">
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                <thead>
                  <tr><th style={{ padding: "4px", textAlign: "left", color: "var(--text-3)" }}>Growth ↓ / WACC →</th>
                    {[a.wacc - 0.02, a.wacc, a.wacc + 0.02].map((w, i) => <th key={i} style={{ padding: "4px", textAlign: "right", color: "var(--text-3)" }}>{(w * 100).toFixed(0)}%</th>)}</tr>
                </thead>
                <tbody>
                  {[a.terminalGrowth - 0.01, a.terminalGrowth, a.terminalGrowth + 0.01].map((g, gi) => (
                    <tr key={gi} style={{ borderTop: "1px solid var(--border)" }}>
                      <td style={{ padding: "4px", color: "var(--text-3)" }}>{(g * 100).toFixed(1)}%</td>
                      {[a.wacc - 0.02, a.wacc, a.wacc + 0.02].map((w, wi) => {
                        const ev = buildDcf(m.ltmRevenue, { ...a, wacc: w, terminalGrowth: g }).ev;
                        const mid = (gi === 1 && wi === 1);
                        return <td key={wi} style={{ padding: "4px", textAlign: "right", fontFamily: "ui-monospace,monospace", fontWeight: mid ? 800 : 400, color: mid ? "#0d9488" : "var(--text)" }}>{money(ev)}</td>;
                      })}
                    </tr>
                  ))}
                </tbody>
              </table>
            </TA.Card>
          </div>
        </div>
      </div>
      <div style={{ marginTop: 14 }}>
        <button style={TA.ghostBtn()} onClick={() => setPage && setPage("valuation")}>← Back to Valuation</button>
      </div>
    </TA.Page>
  );
}

function cell(v, neg, money) {
  if (v === null || v === undefined) return "";
  return neg ? "(" + money(Math.abs(v)) + ")" : money(v);
}
function Out({ k, v, bold }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "5px 0" }}>
      <span style={{ fontSize: 13, fontWeight: bold ? 700 : 400, color: "var(--text-3)" }}>{k}</span>
      <span style={{ fontSize: bold ? 16 : 13.5, fontWeight: bold ? 800 : 600, color: bold ? "#0d9488" : "var(--text)", fontFamily: "ui-monospace,monospace" }}>{v}</span>
    </div>
  );
}

// Full projection used by the table; ev must equal window.computeDcfEV().
function buildDcf(ltmRevenue, a) {
  const years = [];
  let rev = ltmRevenue || 0;
  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);
    years.push({ revenue: rev, ebitda, da: da, da2: da, ebit, tax, nopat, capex, wc, fcf, df, pvfcf: fcf * df });
  }
  const sumPv = years.reduce((s, yr) => s + yr.pvfcf, 0);
  const lastFcf = years.length ? years[years.length - 1].fcf : 0;
  const lastDf = years.length ? years[years.length - 1].df : 1;
  const tv = a.wacc > a.terminalGrowth ? (lastFcf * (1 + a.terminalGrowth)) / (a.wacc - a.terminalGrowth) : 0;
  const pvTv = tv * lastDf;
  return { years, sumPv, tv, pvTv, ev: sumPv + pvTv };
}

Object.assign(window, { DcfModelPage, buildDcf });
