// Transaction Advisory · Page 5 — CIM Builder
// A mini Confidential Information Memorandum generated deterministically from real
// GL data + editable templates (no fabricated numbers). "Generate" fills each
// section from live figures; every section is editable and saved to localStorage.
// "Download as PDF" uses window.print() with a dedicated print stylesheet.
const { useState: useCIM_useState, useEffect: useCIM_useEffect } = React;

function CimBuilderPage({ data, companyProfile, scopedCompanyId, setPage }) {
  const TA = window.TA;
  const m = TA.derive(data, companyProfile);
  if (!m.connected) return <TA.NotConnected what="The CIM assembles from your real financial performance and metrics." />;

  const key = "perdura_cim_" + (scopedCompanyId || "default");
  const [open, setOpen] = useCIM_useState({});
  const [showPrint, setShowPrint] = useCIM_useState(false);
  const [sections, setSections] = useCIM_useState(() => {
    try { const r = localStorage.getItem(key); if (r) return JSON.parse(r); } catch (e) { /* ignore */ }
    return generateCim(m, scopedCompanyId, TA);
  });
  useCIM_useEffect(() => { try { localStorage.setItem(key, JSON.stringify(sections)); } catch (e) { /* ignore */ } }, [sections]);

  const regenerate = () => setSections(generateCim(m, scopedCompanyId, TA));
  const update = (id, text) => setSections(s => s.map(x => x.id === id ? { ...x, text } : x));
  const toggle = (id) => setOpen(o => ({ ...o, [id]: !o[id] }));

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

  return (
    <div>
      <CimPrintStyle />
      <TA.Page title="CIM Builder" badge="Transaction Advisory"
        subtitle="A confidential information memorandum drafted from your live data. Edit any section."
        actions={<>
          <button style={TA.tealBtn()} onClick={regenerate}>Generate CIM</button>
          <button style={TA.ghostBtn()} className="no-print" onClick={() => setShowPrint(true)}>📄 Export as PDF</button>
        </>}>
        {showPrint && <CimPrintModal companyName={m.companyName}
          onClose={() => setShowPrint(false)}
          onPrint={() => { setShowPrint(false); setTimeout(() => window.print(), 60); }} />}
        <div className="cim-doc">
          {/* Print-only cover header (hidden on screen; revealed by @media print). */}
          <div className="cim-print-header" style={{ display: "none" }}>
            <div className="cim-ph-eyebrow">Confidential Information Memorandum</div>
            <h1 className="cim-ph-name">{m.companyName}</h1>
            <div className="cim-ph-date">{new Date().toLocaleDateString("en-US", { month: "long", year: "numeric" })}</div>
            <div className="cim-ph-notice">This document is confidential and intended solely for the recipient. Reproduction or distribution without prior written consent is prohibited.</div>
          </div>
          {/* Running footer + confidential line on every printed page. */}
          <div className="cim-print-footer">{m.companyName} · Confidential Information Memorandum</div>

          {sections.map((sec, i) => (
            <div key={sec.id} className="cim-section" style={{ background: "var(--bg-card)", border: "1px solid var(--border)", borderRadius: 12, marginBottom: 12, overflow: "hidden" }}>
              <button className="cim-toggle" onClick={() => toggle(sec.id)}
                style={{ width: "100%", textAlign: "left", padding: "14px 18px", background: "none", border: "none", cursor: "pointer", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span style={{ fontSize: 14, fontWeight: 700, color: "var(--text)" }}>{i + 1}. {sec.title}</span>
                <span style={{ color: "var(--text-3)" }}>{open[sec.id] ? "▲" : "▼"}</span>
              </button>
              <div className="cim-body" style={{ display: open[sec.id] ? "block" : "none", padding: "0 18px 16px" }}>
                {sec.id === "financials" ? <FinancialTable m={m} money={money} /> :
                 sec.id === "ebitda_bridge" ? <EbitdaSummary m={m} scopedCompanyId={scopedCompanyId} TA={TA} money={money} /> :
                 <textarea value={sec.text} onChange={e => update(sec.id, e.target.value)}
                   style={{ width: "100%", minHeight: 96, 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" }} />}
              </div>
              {/* Print view always renders content regardless of collapse state. */}
              <div className="cim-print-only" style={{ display: "none", padding: "0 18px 16px" }}>
                {sec.id === "financials" ? <FinancialTable m={m} money={money} /> :
                 sec.id === "ebitda_bridge" ? <EbitdaSummary m={m} scopedCompanyId={scopedCompanyId} TA={TA} money={money} /> :
                 <div style={{ whiteSpace: "pre-wrap", fontSize: 13, lineHeight: 1.6 }}>{sec.text}</div>}
              </div>
            </div>
          ))}
        </div>
      </TA.Page>
    </div>
  );
}

function generateCim(m, cid, TA) {
  const money = (v) => TA.money(v, { compact: true });
  const growth = m.revenueGrowthPct != null ? TA.pct(m.revenueGrowthPct) : "n/a";
  const marginTxt = m.ebitdaMargin != null ? TA.pct(m.ebitdaMargin) : "n/a";
  const sector = TA.matchComp(m);
  return [
    { id: "exec_summary", title: "Executive Summary",
      text: `${m.companyName} is a ${sector.toLowerCase()} business generating ${money(m.ltmRevenue)} in last-twelve-month revenue with ${money(m.ltmEbitda)} of EBITDA (a ${marginTxt} margin). The company is presented on a confidential basis to qualified parties evaluating an acquisition. Year-over-year revenue growth is ${growth}.` },
    { id: "highlights", title: "Investment Highlights",
      text: [
        `• ${money(m.ltmRevenue)} LTM revenue with a ${marginTxt} EBITDA margin`,
        `• ${m.revenueGrowthPct != null && m.revenueGrowthPct > 0 ? "Positive" : "Stable"} revenue trajectory (${growth} YoY)`,
        m.topCustomerPct != null ? `• Largest customer represents ${TA.pct(m.topCustomerPct)} of revenue` : "• Diversified customer base",
        `• ${m.yearsOfData != null ? m.yearsOfData.toFixed(1) : "Multiple"} years of clean, mapped financial history`,
        "• Experienced management team in place (edit to expand)",
        "• Clear organic and inorganic growth runway (edit to expand)",
      ].join("\n") },
    { id: "overview", title: "Business Overview",
      text: `${m.companyName} operates in the ${sector.toLowerCase()} sector. [Describe the business model, core offering, customers served, geographic footprint, and company history here. This section is a starting template — edit freely.]` },
    { id: "financials", title: "Financial Performance", text: "" },
    { id: "ebitda_bridge", title: "Adjusted EBITDA Bridge", text: "" },
    { id: "growth", title: "Growth Opportunities",
      text: "• Expand into adjacent segments or geographies\n• Increase share of recurring / contracted revenue\n• Operational leverage as revenue scales\n• Selective bolt-on acquisitions\n[Edit to tailor to your business.]" },
    { id: "management", title: "Management Team",
      text: "[List key management, tenure, and roles. Manual entry.]" },
    { id: "transaction", title: "Transaction Overview",
      text: `The shareholders are exploring a sale. Based on comparable ${sector.toLowerCase()} multiples applied to adjusted EBITDA and revenue, the indicative value range is presented separately in the Valuation Model. Structure, terms, and timing are open for discussion with qualified parties.` },
  ];
}

function FinancialTable({ m, money }) {
  const years = m.revAnnual || [];
  const 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: 13 }}>
      <thead><tr style={{ color: "var(--text-3)", fontSize: 11 }}>
        <th style={{ textAlign: "left", padding: "5px 8px" }}></th>
        {labels.map((l, i) => <th key={i} style={{ textAlign: "right", padding: "5px 8px" }}>{l}</th>)}
      </tr></thead>
      <tbody>
        <tr style={{ borderTop: "1px solid var(--border)" }}><td style={{ padding: "6px 8px", fontWeight: 600 }}>Revenue</td>
          {years.map((y, i) => <td key={i} style={{ padding: "6px 8px", textAlign: "right", fontFamily: "ui-monospace,monospace" }}>{money(y.sum)}</td>)}</tr>
        <tr style={{ borderTop: "1px solid var(--border)" }}><td style={{ padding: "6px 8px", fontWeight: 600 }}>EBITDA</td>
          {eb.map((y, i) => <td key={i} style={{ padding: "6px 8px", textAlign: "right", fontFamily: "ui-monospace,monospace" }}>{money(y.sum)}</td>)}</tr>
      </tbody>
    </table>
  );
}

function EbitdaSummary({ m, scopedCompanyId, TA, money }) {
  const addbacks = TA.loadAddbacks(scopedCompanyId);
  const total = addbacks.reduce((s, a) => s + (Number(a.amount) || 0), 0);
  const adj = (m.ltmEbitda || 0) + total;
  return (
    <div style={{ fontSize: 13 }}>
      <Row k="Reported EBITDA (GL)" v={money(m.ltmEbitda)} />
      {addbacks.filter(a => Number(a.amount)).map(a => <Row key={a.id} k={"+ " + a.description} v={money(Number(a.amount))} sub={a.rationale} />)}
      <div style={{ borderTop: "1px solid var(--border-strong,var(--border))", margin: "6px 0" }} />
      <Row k="Adjusted EBITDA" v={money(adj)} bold />
    </div>
  );
}
function Row({ k, v, sub, bold }) {
  return (
    <div style={{ padding: "3px 0" }}>
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <span style={{ fontWeight: bold ? 700 : 400, color: "var(--text)" }}>{k}</span>
        <span style={{ fontFamily: "ui-monospace,monospace", fontWeight: bold ? 800 : 500, color: bold ? "#0d9488" : "var(--text)" }}>{v}</span>
      </div>
      {sub && <div style={{ fontSize: 11, color: "var(--text-3)", fontStyle: "italic" }}>{sub}</div>}
    </div>
  );
}

function CimPrintStyle() {
  return (
    <style>{`
      .cim-print-footer { display: none; }
      @media print {
        @page { size: Letter; margin: 16mm 16mm 20mm; }
        body * { visibility: hidden; }
        .cim-doc, .cim-doc * { visibility: visible; }
        .cim-doc { position: absolute; left: 0; top: 0; width: 100%; }
        .cim-toggle { padding: 6px 0 !important; }
        .cim-toggle span:last-child, .cim-body { display: none !important; }
        .cim-print-only { display: block !important; }
        /* Professional confidential cover header on the first page. */
        .cim-print-header { display: block !important; text-align: center; padding-bottom: 22px; border-bottom: 2px solid #0d2040; margin-bottom: 8px; page-break-after: always; }
        .cim-ph-eyebrow { font-size: 10pt; font-weight: 700; color: #999; text-transform: uppercase; letter-spacing: 2px; margin-bottom: 10px; }
        .cim-ph-name { font-size: 24pt; font-weight: 800; color: #0d2040; margin: 0; }
        .cim-ph-date { font-size: 11pt; color: #6475a0; margin-top: 8px; }
        .cim-ph-notice { margin: 16px auto 0; max-width: 460px; font-size: 8.5pt; color: #999; border: 1px solid #e9ecef; padding: 8px 16px; }
        .cim-section { border: none !important; page-break-inside: avoid; margin-bottom: 18px; }
        .cim-toggle span:first-child { font-size: 13pt !important; color: #0d2040 !important; }
        /* Running confidential footer on every printed page. */
        .cim-print-footer { display: block !important; position: fixed; bottom: 6mm; left: 0; right: 0; text-align: center; font-size: 8.5pt; color: #999; font-family: ui-monospace, monospace; }
        textarea { display: none !important; }
      }
    `}</style>
  );
}

// Pre-print instructions modal (JSX). Prefers the shared window.PrintInstructionsModal
// when available; otherwise renders this self-contained fallback.
function CimPrintModal({ companyName, onClose, onPrint }) {
  if (window.PrintInstructionsModal) {
    return React.createElement(window.PrintInstructionsModal, { docType: "CIM", accent: "#00b894", onClose, onPrint });
  }
  const line = (t) => (
    <div style={{ display: "flex", gap: 8, marginTop: 6 }}>
      <span style={{ color: "#00b894", fontWeight: 700 }}>•</span><span>{t}</span>
    </div>
  );
  return (
    <div className="no-print" onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.5)", zIndex: 100000, display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: "#fff", borderRadius: 16, padding: 32, width: 440, maxWidth: "92vw", boxShadow: "0 24px 64px rgba(0,0,0,.3)" }}>
        <div style={{ fontSize: 18, fontWeight: 800, color: "#0d2040", marginBottom: 8 }}>Export CIM as PDF</div>
        <div style={{ fontSize: 13, color: "#6475a0", marginBottom: 14, lineHeight: 1.6 }}>Your browser will open the print dialog. To save as a PDF instead of printing:</div>
        <div style={{ fontSize: 12.5, color: "#1a2540", lineHeight: 1.5, background: "#f7f8fb", border: "1px solid #e9ecef", borderRadius: 10, padding: "12px 14px", marginBottom: 20 }}>
          {line("Chrome / Edge — choose “Save as PDF” in the Destination dropdown")}
          {line("Safari — click the “PDF” button at the bottom-left, then “Save as PDF”")}
          {line("Firefox — choose “Microsoft Print to PDF” (or “Save to PDF”)")}
        </div>
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
          <button onClick={onClose} style={{ padding: "10px 20px", border: "1px solid #e9ecef", borderRadius: 8, background: "#fff", cursor: "pointer", fontSize: 13, fontWeight: 600 }}>Cancel</button>
          <button onClick={onPrint} style={{ padding: "10px 20px", background: "#00b894", color: "#fff", border: "none", borderRadius: 8, cursor: "pointer", fontWeight: 700, fontSize: 13 }}>Open Print Dialog →</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CimBuilderPage });
