// Transaction Advisory · Page 3 — EBITDA Analysis
// A banker-style EBITDA bridge. Net Income and EBITDA are REAL (from the GL —
// data.net_income_ltm and pl.ebitda). The GL rolls D&A / interest / tax into opex
// and cannot separate them (data-live.js), so those bridge lines are owner-entered
// (never auto-filled). Normalizing add-backs are editable and saved to
// localStorage keyed perdura_addbacks_{companyId}. GL accounts that look like
// add-backs are surfaced with a ⚠️ review flag.
const { useState: useEB_useState, useEffect: useEB_useEffect } = React;

function EbitdaAnalysisPage({ data, companyProfile, scopedCompanyId, setPage }) {
  const TA = window.TA;
  const m = TA.derive(data, companyProfile);
  if (!m.connected) return <TA.NotConnected what="The EBITDA bridge starts from your real reported net income and EBITDA." />;

  // Bridge lines between Net Income and reported EBITDA — GL cannot split these,
  // so they are manual inputs stored alongside the company's DCF-style overrides.
  const bridgeKey = "perdura_ebitda_bridge_" + (scopedCompanyId || "default");
  const [bridge, setBridge] = useEB_useState(() => {
    try { const r = localStorage.getItem(bridgeKey); if (r) return JSON.parse(r); } catch (e) { /* ignore */ }
    return { interest: 0, tax: 0, da: 0 };
  });
  useEB_useEffect(() => { try { localStorage.setItem(bridgeKey, JSON.stringify(bridge)); } catch (e) { /* ignore */ } }, [bridge]);

  const [addbacks, setAddbacks] = useEB_useState(() => TA.loadAddbacks(scopedCompanyId));
  useEB_useEffect(() => { TA.saveAddbacks(scopedCompanyId, addbacks); }, [addbacks]);

  const signals = TA.flagAddbackSignals(data);
  const money = (v) => TA.money(v, { compact: false });

  // Reported EBITDA is the real anchor. We show the manual bridge as reconciliation
  // context; Adjusted EBITDA builds on the real reported EBITDA + normalizing add-backs.
  const reportedEbitda = m.ltmEbitda || 0;
  const addbackTotal = addbacks.reduce((s, a) => s + (Number(a.amount) || 0), 0);
  const adjEbitda = reportedEbitda + addbackTotal;
  const adjMargin = m.ltmRevenue > 0 ? adjEbitda / m.ltmRevenue : null;

  const setBridgeVal = (k, v) => setBridge(b => ({ ...b, [k]: Number(v) || 0 }));
  const updateAddback = (id, patch) => setAddbacks(list => list.map(a => a.id === id ? { ...a, ...patch } : a));
  const removeAddback = (id) => setAddbacks(list => list.filter(a => a.id !== id));
  const addCustom = () => setAddbacks(list => [...list, { id: "custom_" + list.length + "_" + (list.reduce((s, a) => s + a.description.length, 1)), description: "Custom add-back", amount: 0, category: "One-time", rationale: "", locked: false }]);

  const impliedNi = reportedEbitda - (Number(bridge.interest) || 0) - (Number(bridge.tax) || 0) - (Number(bridge.da) || 0);

  return (
    <TA.Page title="EBITDA Analysis" badge="Transaction Advisory"
      subtitle="Reported and adjusted EBITDA the way an investment banker presents it.">
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, alignItems: "start" }}>
        <TA.Card title="EBITDA bridge">
          <Line k="Net Income (implied)" v={money(impliedNi)} sub="reported EBITDA less the add-backs below" />
          <div style={{ fontSize: 11.5, color: "var(--text-3)", margin: "6px 0 4px" }}>Add back — enter from your tax return / trial balance (the GL lumps these into opex):</div>
          <BridgeInput label="Interest expense" value={bridge.interest} onChange={v => setBridgeVal("interest", v)} />
          <BridgeInput label="Tax expense" value={bridge.tax} onChange={v => setBridgeVal("tax", v)} />
          <BridgeInput label="Depreciation & amortization" value={bridge.da} onChange={v => setBridgeVal("da", v)} />
          <Divider />
          <Line k="EBITDA (reported)" v={money(reportedEbitda)} bold accent sub="real — from your general ledger" />
        </TA.Card>

        <TA.Card title="Normalizing adjustments">
          {addbacks.map(a => (
            <div key={a.id} style={{ padding: "10px 0", borderBottom: "1px solid var(--border)" }}>
              <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <input value={a.description} onChange={e => updateAddback(a.id, { description: e.target.value })}
                  style={inp({ flex: 1 })} />
                <span style={{ color: "var(--text-3)" }}>+$</span>
                <input type="number" value={a.amount} onChange={e => updateAddback(a.id, { amount: e.target.value })}
                  style={inp({ width: 110, textAlign: "right", fontFamily: "ui-monospace,monospace" })} />
                <button onClick={() => removeAddback(a.id)} style={{ border: "none", background: "none", cursor: "pointer", color: "var(--text-3)", fontSize: 15 }}>✕</button>
              </div>
              <div style={{ display: "flex", gap: 8, marginTop: 6 }}>
                <select value={a.category} onChange={e => updateAddback(a.id, { category: e.target.value })} style={inp({ width: 140, fontSize: 12 })}>
                  {["One-time", "Owner", "Non-cash", "Related-party"].map(c => <option key={c} value={c}>{c}</option>)}
                </select>
                <input value={a.rationale} placeholder="Rationale (shown in CIM)" onChange={e => updateAddback(a.id, { rationale: e.target.value })}
                  style={inp({ flex: 1, fontSize: 12 })} />
              </div>
            </div>
          ))}
          <button onClick={addCustom} style={{ ...TA.ghostBtn({ marginTop: 10, fontSize: 12.5 }) }}>+ Add custom add-back</button>
          <Divider />
          <Line k="Total add-backs" v={money(addbackTotal)} />
          <Line k="Adjusted EBITDA" v={money(adjEbitda)} bold accent />
          <Line k="Adjusted EBITDA margin" v={adjMargin != null ? TA.pct(adjMargin) : "—"} />
        </TA.Card>
      </div>

      {signals.length > 0 && (
        <div style={{ marginTop: 18 }}>
          <TA.Card title="Possible add-backs detected in your GL">
            <div style={{ fontSize: 12, color: "var(--text-3)", marginBottom: 10 }}>These accounts match common add-back patterns. Review — they may warrant a normalizing adjustment above.</div>
            {signals.map((s, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 0", borderBottom: "1px solid var(--border)" }}>
                <span>⚠️</span>
                <div style={{ flex: 1 }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: "var(--text)" }}>{s.account}</span>
                  <span style={{ fontSize: 11.5, color: "#d97706", marginLeft: 8 }}>{s.signal} — review</span>
                </div>
                {s.amount != null && <span style={{ fontFamily: "ui-monospace,monospace", fontSize: 12.5, color: "var(--text-3)" }}>{money(s.amount)}</span>}
              </div>
            ))}
          </TA.Card>
        </div>
      )}

      <div style={{ marginTop: 14, display: "flex", gap: 8 }}>
        <button style={TA.tealBtn()} onClick={() => setPage && setPage("valuation")}>Apply to valuation →</button>
      </div>
    </TA.Page>
  );
}

function inp(extra) {
  return { padding: "6px 9px", border: "1px solid var(--border)", borderRadius: 6, background: "var(--bg-card)", color: "var(--text)", fontSize: 13, ...(extra || {}) };
}
function Line({ k, v, sub, bold, accent }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "5px 0" }}>
      <span style={{ fontSize: bold ? 13.5 : 13, fontWeight: bold ? 700 : 400, color: "var(--text-3)" }}>
        {k}{sub && <span style={{ fontSize: 11, marginLeft: 6, fontStyle: "italic" }}>({sub})</span>}
      </span>
      <span style={{ fontSize: bold ? 15 : 13.5, fontWeight: bold ? 800 : 600, color: accent ? "#0d9488" : "var(--text)", fontFamily: "ui-monospace,monospace" }}>{v}</span>
    </div>
  );
}
function BridgeInput({ label, value, onChange }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "3px 0" }}>
      <span style={{ fontSize: 13, color: "var(--text-3)" }}>+ {label}</span>
      <span><span style={{ color: "var(--text-3)", fontSize: 12 }}>$</span>
        <input type="number" value={value} onChange={e => onChange(e.target.value)}
          style={inp({ width: 110, textAlign: "right", fontFamily: "ui-monospace,monospace" })} /></span>
    </div>
  );
}
function Divider() { return <div style={{ borderTop: "1px solid var(--border-strong,var(--border))", margin: "8px 0" }} />; }

Object.assign(window, { EbitdaAnalysisPage });
