// app/icmemo.jsx — IC Memo (Grove visual style)
const { useState: useSIC } = React;

// ─── Tokens (Grove palette) ───────────────────────────────────────────────────
const IC = {
  navy:  '#0d1f35',
  navy2: '#1b3e60',
  blue:  '#1f57c4',
  bg:    '#e9ecf3',
  panel: '#ffffff',
  line:  '#dde3ec',
  line2: '#edf0f7',
  muted: '#607080',
  faint: '#8fa0b2',
  pos:   '#096b38',
  neg:   '#c12828',
  warn:  '#a86800',
  gold:  '#c49010',
  sans:  'Inter,"Helvetica Neue",system-ui,sans-serif',
  serif: '"Lora",Georgia,serif',
  mono:  '"IBM Plex Mono",ui-monospace,monospace',
};

// ─── Formatters ───────────────────────────────────────────────────────────────
const _m  = (v) => (v==null||isNaN(+v)) ? '—' : '$'+Math.round(+v).toLocaleString();
const _ms = (v) => {
  if (v==null||isNaN(+v)) return '—';
  const n=+v, a=Math.abs(n), s=n<0?'-':'';
  if (a>=1e9) return s+'$'+(a/1e9).toFixed(1)+'B';
  if (a>=1e6) return s+'$'+(a/1e6).toFixed(1)+'M';
  if (a>=1e3) return s+'$'+Math.round(a/1e3)+'K';
  return s+'$'+Math.round(a).toLocaleString();
};
const _p  = (v,d=1) => (v==null||isNaN(+v)) ? '—' : (+v*100).toFixed(d)+'%';
const _r  = (v,d=2) => (v==null||isNaN(+v)) ? '—' : (+v).toFixed(d)+'%';
const _x  = (v,d=2) => (v==null||isNaN(+v)) ? '—' : (+v).toFixed(d)+'x';
const _n  = (v,d=2) => (v==null||isNaN(+v)) ? '—' : (+v).toFixed(d);

// ─── Panel header ─────────────────────────────────────────────────────────────
function PanelHdr({ children }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:6, padding:'4px 11px',
      borderBottom:'1px solid '+IC.line, fontSize:10, fontWeight:700,
      letterSpacing:'.08em', textTransform:'uppercase', color:IC.navy,
      fontFamily:IC.sans, lineHeight:1.5 }}>
      {children}
    </div>
  );
}

// ─── Data row ─────────────────────────────────────────────────────────────────
function DR({ label, value, strong, sep }) {
  return (
    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center',
      padding:'2px 11px', borderBottom:'1px solid '+IC.line2,
      borderTop: sep ? '1px solid '+IC.line : 'none' }}>
      <span style={{ fontSize:11, color:IC.muted }}>{label}</span>
      <span style={{ fontSize:11, fontWeight:strong?600:500, color:IC.navy,
        fontVariantNumeric:'tabular-nums' }}>{value}</span>
    </div>
  );
}

// ─── Metric cell ──────────────────────────────────────────────────────────────
function MetricCell({ label, value, color, last }) {
  return (
    <div style={{ padding:'0 10px', borderRight: last?'none':'1px solid '+IC.line2,
      display:'flex', flexDirection:'column' }}>
      <div style={{ marginBottom:2 }}>
        <span style={{ fontSize:8.5, fontWeight:600, letterSpacing:'.07em',
          textTransform:'uppercase', color:IC.muted, lineHeight:1.2, display:'block' }}>{label}</span>
      </div>
      <div style={{ fontSize:16, fontWeight:700, color:color||IC.navy, lineHeight:1,
        letterSpacing:'-.02em', fontVariantNumeric:'tabular-nums' }}>{value}</div>
    </div>
  );
}

// ─── Capital structure donut ──────────────────────────────────────────────────
function CapDonut({ uw, basis }) {
  if (!uw) return null;
  const debt   = uw.acqProceeds||0;
  const equity = uw.initialEquity||(basis-debt);
  const total  = debt+equity; if (!total) return null;
  const eqPct  = equity/total;
  const r=40, stroke=11, cx=52, cy=52, size=104;
  const circ   = 2*Math.PI*r;
  const eqDash = eqPct*circ;
  const ltv    = uw.price>0 ? debt/uw.price : null;
  const stabRow = uw.rows ? uw.rows[Math.min(uw.stabYear||3,uw.hold)] : null;
  const dscr    = stabRow ? stabRow.dscr : null;
  return (
    <div style={{ display:'flex', gap:10, alignItems:'center', padding:'4px 11px 6px' }}>
      <div style={{ flexShrink:0 }}>
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
          <circle cx={cx} cy={cy} r={r} fill="none" stroke={IC.navy} strokeWidth={stroke}
            strokeDasharray={`${eqDash} ${circ}`} strokeDashoffset={0}
            transform={`rotate(-90 ${cx} ${cy})`} />
          <circle cx={cx} cy={cy} r={r} fill="none" stroke={IC.blue} strokeWidth={stroke}
            strokeDasharray={`${circ-eqDash} ${circ}`} strokeDashoffset={-eqDash}
            transform={`rotate(-90 ${cx} ${cy})`} />
          <text x={cx} y={cy-5} textAnchor="middle" fontSize="7" fontWeight="700"
            fill={IC.faint} fontFamily={IC.sans} letterSpacing=".07em">TOTAL BASIS</text>
          <text x={cx} y={cy+9} textAnchor="middle" fontSize="13" fontWeight="700"
            fill={IC.navy} fontFamily={IC.sans}>{_ms(basis)}</text>
        </svg>
      </div>
      <div style={{ flex:1 }}>
        {[{ label:'Equity', amt:equity, pct:eqPct, col:IC.navy },
          { label:'Sr. Debt', amt:debt, pct:1-eqPct, col:IC.blue }].map(({ label,amt,pct,col }) => (
          <div key={label} style={{ display:'flex', alignItems:'center', gap:6,
            padding:'2px 0', borderBottom:'1px solid '+IC.line2 }}>
            <div style={{ width:8, height:8, borderRadius:'50%', background:col, flexShrink:0 }}/>
            <span style={{ fontSize:10.5, color:IC.muted, flex:1 }}>{label}</span>
            <span style={{ fontSize:11, fontWeight:600, color:IC.navy, fontVariantNumeric:'tabular-nums' }}>
              {_ms(amt)}<span style={{ fontSize:9.5, color:IC.faint, marginLeft:3 }}>({_p(pct,0)})</span>
            </span>
          </div>
        ))}
        {uw.acqLoan && (
          [['LTV', ltv!=null?_p(ltv):'—'],
           ['Interest Rate', (uw.acqLoan.rate*100).toFixed(2)+'%'],
           ['Amortization', Math.round(uw.acqLoan.amMonths/12)+' Yrs'],
           ['DSCR (Stab.)', dscr!=null?(_n(dscr)+'x'):'—']
          ].map(([l,v]) => (
            <div key={l} style={{ display:'flex', alignItems:'center', gap:6,
              padding:'2px 0', borderBottom:'1px solid '+IC.line2 }}>
              <div style={{ width:8, height:8, borderRadius:'50%', background:'transparent',
                border:'1.5px solid '+IC.line, flexShrink:0 }}/>
              <span style={{ fontSize:10.5, color:IC.muted, flex:1 }}>{l}</span>
              <span style={{ fontSize:11, fontWeight:600, color:IC.navy,
                fontVariantNumeric:'tabular-nums' }}>{v}</span>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

// ─── Scenario analysis ────────────────────────────────────────────────────────
function ScenarioAnalysis({ deal, uw }) {
  if (!uw) return (
    <div style={{ fontSize:10, color:IC.faint, fontStyle:'italic', padding:'8px 0' }}>
      Complete Full Underwriting to enable scenario analysis.
    </div>
  );

  const run = (ov) => { try { return window.computeScenario ? window.computeScenario(deal, ov) : null; } catch(e) { return null; } };

  const gpr  = uw.gprGrowth||0.03;
  const opex = uw.opexGrowth||0.025;
  const exit = uw.exitCap||0.065;

  const scenarios = [
    { label:'WEAK', color:IC.neg,
      desc:`Rent ${_p(Math.max(0,gpr-.01))} · OpEx ${_p(opex+.01)} · Exit ${_r((exit+.005)*100)}`,
      r: run({ gprGrowth:Math.max(0,gpr-.01), opexGrowth:opex+.01, exitCap:exit+.005 }) },
    { label:'BASE', color:IC.navy,
      desc:'Current underwriting assumptions',
      r: { dealIRR:uw.irr, equityMultiple:uw.equityMultiple, avgDealYield:uw.avgYield,
           lpIRR:null, avgLpYield:null, lpMultiple:null, gpPromote:null } },
    { label:'BEST', color:IC.pos,
      desc:`Rent ${_p(gpr+.01)} · OpEx ${_p(Math.max(0,opex-.005))} · Exit ${_r((Math.max(.04,exit-.0025))*100)}`,
      r: run({ gprGrowth:gpr+.01, opexGrowth:Math.max(0,opex-.005), exitCap:Math.max(.04,exit-.0025) }) },
  ];

  // Augment BASE with LP data
  if (window.computeLP) {
    try {
      const lp = window.computeLP(uw, { pref:deal.lpPref, split:deal.lpSplit });
      if (lp) Object.assign(scenarios[1].r, {
        lpIRR:lp.lpIRR, avgLpYield:lp.avgLpYield, lpMultiple:lp.lpMultiple, gpPromote:lp.gpPromote
      });
    } catch(e) {}
  }

  const hasLP = scenarios.some(s => s.r && s.r.lpIRR != null);
  const hasGP = scenarios.some(s => s.r && s.r.gpPromote != null);

  const scColors = [IC.neg, IC.navy, IC.pos];
  const irrColor = (r) => r&&r.dealIRR!=null ? (r.dealIRR>=.18?IC.pos:r.dealIRR<.12?IC.neg:IC.warn) : IC.navy;
  const lpIrrColor = (r) => r&&r.lpIRR!=null ? (r.lpIRR>=.15?IC.pos:r.lpIRR<.1?IC.neg:IC.warn) : IC.navy;

  const ROWS = [
    { type:'section', label:'DEAL & LP RETURNS' },
    { type:'row', label:'Deal IRR',           fmt:(r,i)=>r&&r.dealIRR!=null?_p(r.dealIRR):'—',        colorFn:irrColor, bold:true },
    { type:'row', label:'Avg Deal Yield',      fmt:(r,i)=>r&&(r.avgDealYield||r.avgCOC)!=null?_p(r.avgDealYield||r.avgCOC):'—', scIdx:true },
    { type:'row', label:'Equity Multiple',     fmt:(r,i)=>r&&r.equityMultiple!=null?_x(r.equityMultiple):'—', scIdx:true },
    ...(hasLP ? [
      { type:'row', label:'LP IRR',             fmt:(r,i)=>r&&r.lpIRR!=null?_p(r.lpIRR):'—',          colorFn:lpIrrColor, bold:true },
      { type:'row', label:'Avg LP Yield',        fmt:(r,i)=>r&&r.avgLpYield!=null?_p(r.avgLpYield):'—', scIdx:true },
      { type:'row', label:'LP Equity Multiple',  fmt:(r,i)=>r&&r.lpMultiple!=null?_x(r.lpMultiple):'—', scIdx:true },
    ] : []),
    ...(hasGP ? [
      { type:'section', label:'GP RETURNS' },
      { type:'row', label:'Total GP Promote',   fmt:(r,i)=>r&&r.gpPromote!=null?_m(r.gpPromote):'—',   scIdx:true },
    ] : []),
  ];

  return (
    <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>
      <thead>
        <tr>
          <th style={{ textAlign:'left', fontSize:9, fontWeight:700, letterSpacing:'.08em',
            textTransform:'uppercase', color:IC.faint, padding:'0 0 4px', width:185 }}>Metric</th>
          {scenarios.map(s => (
            <th key={s.label} style={{ textAlign:'center', padding:'0 4px 3px' }}>
              <div style={{ fontSize:10.5, fontWeight:700, letterSpacing:'.07em', color:s.color }}>{s.label}</div>
              <div style={{ fontSize:8.5, color:IC.faint, marginTop:1, lineHeight:1.3 }}>{s.desc}</div>
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {ROWS.map((row,i) => row.type==='section' ? (
          <tr key={i}>
            <td colSpan={4} style={{ background:IC.navy, color:'#fff', fontSize:9, fontWeight:700,
              letterSpacing:'.1em', textTransform:'uppercase', padding:'2.5px 9px' }}>
              <span style={{ display:'inline-block', width:8, height:8, borderRadius:2,
                background:IC.blue, marginRight:6, verticalAlign:'middle' }}/>
              {row.label}
            </td>
          </tr>
        ) : (
          <tr key={i}>
            <td style={{ fontSize:11.5, color:'#2b3d52', padding:'3px 0',
              borderBottom:'1px solid '+IC.line2 }}>{row.label}</td>
            {scenarios.map((s,si) => (
              <td key={s.label} style={{ textAlign:'center', padding:'3px 4px',
                borderBottom:'1px solid '+IC.line2, fontVariantNumeric:'tabular-nums',
                fontSize:row.bold?12:11.5, fontWeight:row.bold?700:600,
                color: row.colorFn ? row.colorFn(s.r) : scColors[si] }}>
                {row.fmt(s.r, si)}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ─── Return decomposition ─────────────────────────────────────────────────────
function ReturnDecomp({ uw }) {
  if (!uw||!uw.totalDistributions) return null;
  const exit = uw.netSaleProceeds||0;
  const opCF = Math.max(0,(uw.totalDistributions||0)-exit);
  const total = opCF+exit; if (!total) return null;
  const opP = Math.round(opCF/total*100);
  const exP = 100-opP;
  return (
    <div style={{ padding:'5px 11px 7px' }}>
      <div style={{ height:26, borderRadius:3, overflow:'hidden', display:'flex', marginBottom:5 }}>
        <div style={{ width:opP+'%', background:IC.navy, display:'flex', alignItems:'center',
          justifyContent:'center', minWidth:24 }}>
          <span style={{ fontSize:13, fontWeight:700, color:'#fff' }}>{opP}%</span>
        </div>
        <div style={{ flex:1, background:IC.blue, display:'flex', alignItems:'center',
          justifyContent:'center', minWidth:24 }}>
          <span style={{ fontSize:13, fontWeight:700, color:'#fff' }}>{exP}%</span>
        </div>
      </div>
      <div style={{ display:'flex' }}>
        {[['Operating Cash Flows', opCF, opP], ['Exit Proceeds', exit, exP]].map(([label,amt,pct]) => (
          <div key={label} style={{ flex:pct }}>
            <div style={{ fontSize:8.5, fontWeight:600, letterSpacing:'.08em', textTransform:'uppercase',
              color:IC.muted, lineHeight:1.2 }}>{label}</div>
            <div style={{ fontSize:13, fontWeight:700, color:IC.navy, marginTop:2,
              fontVariantNumeric:'tabular-nums' }}>{_ms(amt)}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Underwriting assumptions ─────────────────────────────────────────────────
function UWAssumptions({ uw }) {
  if (!uw) return null;
  const items = [
    { icon:'chart',  label:'Rent Growth',    val:_p(uw.gprGrowth)+' /yr' },
    { icon:'sun',    label:'Expense Growth', val:_p(uw.opexGrowth)+' /yr' },
    { icon:'grid',   label:'Stab. Vacancy',  val:_p(uw.stabVac) },
    { icon:'arrow',  label:'Exit Cap Rate',  val:_r(uw.exitCap*100) },
    { icon:'clock',  label:'Hold Period',    val:uw.hold+' Years' },
  ];
  return (
    <div style={{ display:'flex', height:'100%' }}>
      {items.map((item,i) => (
        <div key={item.label} style={{ flex:1, display:'flex', flexDirection:'column',
          alignItems:'center', textAlign:'center', padding:'5px 3px 6px',
          borderRight: i<items.length-1 ? '1px solid '+IC.line : 'none' }}>
          <div style={{ width:22, height:22, background:'#f2f4f8', borderRadius:5,
            display:'flex', alignItems:'center', justifyContent:'center', marginBottom:4 }}>
            <Icon name={item.icon} size={13} style={{ color:IC.navy2 }} />
          </div>
          <div style={{ fontSize:8, fontWeight:600, letterSpacing:'.07em', textTransform:'uppercase',
            color:IC.muted, marginBottom:3, lineHeight:1.3, minHeight:16,
            display:'flex', alignItems:'flex-end', justifyContent:'center' }}>{item.label}</div>
          <div style={{ fontSize:13, fontWeight:700, color:IC.navy, lineHeight:1 }}>{item.val}</div>
        </div>
      ))}
    </div>
  );
}

// ─── Operating forecast ───────────────────────────────────────────────────────
function OperatingForecast({ uw }) {
  if (!uw||!uw.rows) return null;
  const maxY = Math.min(uw.hold, 5);
  const years = [];
  for (let y=1; y<=maxY; y++) {
    const row=uw.rows[y]; if(!row) continue;
    years.push({ y, noi:row.noi, gpr:row.gpr,
      econ:1-(uw.econVacForYear?uw.econVacForYear(y):uw.stabVac),
      margin:row.gpr>0?row.noi/row.gpr:null,
      stab:y>=uw.stabYear });
  }
  if (!years.length) return null;
  const METRICS = [
    { label:'NOI ($M)',        fmt:(r)=>r.noi!=null?('$'+(r.noi/1e6).toFixed(2)+'M'):'—',                                                    bold:true },
    { label:'YOY Growth',      fmt:(r,i)=>{ if(i===0||!years[i-1]||!years[i-1].noi) return '—'; return _p((r.noi-years[i-1].noi)/years[i-1].noi,1); }, green:true },
    { label:'Econ. Occupancy', fmt:(r)=>r.econ!=null?_p(r.econ,0):'—',                                                                        blue:true },
    { label:'NOI Margin',      fmt:(r)=>r.margin!=null?_p(r.margin,0):'—',                                                                    accent:true },
  ];
  return (
    <table style={{ width:'100%', borderCollapse:'collapse', tableLayout:'fixed' }}>
      <thead>
        <tr>
          <th style={{ textAlign:'left', fontSize:8.5, fontWeight:700, letterSpacing:'.07em',
            textTransform:'uppercase', color:IC.faint, padding:'3px 7px 3px 0',
            borderBottom:'1.5px solid '+IC.line }}>Year</th>
          {years.map(r => (
            <th key={r.y} style={{ textAlign:'right', fontSize:9.5, fontWeight:700,
              color:r.stab?IC.pos:IC.navy, padding:'3px 7px',
              borderBottom:'1.5px solid '+IC.line, fontVariantNumeric:'tabular-nums' }}>Y{r.y}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {METRICS.map(m => (
          <tr key={m.label}>
            <td style={{ fontSize:8.5, fontWeight:700, letterSpacing:'.06em', textTransform:'uppercase',
              color:IC.muted, padding:'4px 7px 4px 0', borderBottom:'1px solid '+IC.line2 }}>{m.label}</td>
            {years.map((r,i) => (
              <td key={r.y} style={{ textAlign:'right', fontVariantNumeric:'tabular-nums',
                padding:'4px 7px', borderBottom:'1px solid '+IC.line2,
                fontSize:m.bold?12:11, fontWeight:m.bold?700:500,
                color:m.bold?(r.stab?IC.pos:IC.navy):m.green?IC.pos:m.blue?IC.navy2:IC.blue }}>
                {m.fmt(r,i)}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ─── Bullet ───────────────────────────────────────────────────────────────────
function Bul({ text, tone }) {
  const bg = tone==='pos'?IC.pos:tone==='neg'?IC.neg:IC.blue;
  return (
    <div style={{ display:'flex', gap:7, marginBottom:4 }}>
      <div style={{ flexShrink:0, width:5, height:5, borderRadius:'50%', background:bg, marginTop:5 }}/>
      <div style={{ fontSize:10, lineHeight:1.4, color:IC.navy }}>{text}</div>
    </div>
  );
}

// ─── IC Memo Sheet ────────────────────────────────────────────────────────────
function ICMemoSheet({ deal }) {
  const m     = window.computeMetrics ? window.computeMetrics(deal) : {};
  const hasUW = window.hasUWInputs && window.hasUWInputs(deal);
  const uw    = hasUW && window.computeUW ? window.computeUW(deal) : null;
  const caps  = window.displayCaps ? window.displayCaps(deal) : { goingIn:m.goingInCap, stab:m.stabilizedCap };
  const memo  = (deal.memo&&deal.memo.data) ? deal.memo.data : {};
  const mr    = (deal.marketReview&&deal.marketReview.status==='done') ? deal.marketReview.data : null;

  const basis   = (+deal.purchasePrice||0)+(+deal.capex||0);
  const stabRow = uw&&uw.rows ? uw.rows[Math.min(uw.stabYear||3,uw.hold)] : null;
  const yr1Row  = uw&&uw.rows ? uw.rows[1] : null;
  const irr     = uw ? uw.irr : null;
  const em      = uw ? uw.equityMultiple : null;
  const dscr    = stabRow ? stabRow.dscr : null;
  const yoc     = stabRow ? stabRow.yieldOnCost : null;
  const ltv     = uw&&uw.price>0 ? (uw.acqProceeds||0)/uw.price : null;

  const statusLabel = { 'New Deal':'Early Stage','Quick UW':'Early Stage','Full UW':'Full UW',
    'Excel UW':'Full UW','LOI Submitted':'LOI Stage','Under Contract':'Under Contract' }[deal.stage]||'IC Review';

  const todayStr = (()=>{ try{return fmtDate(window.ALTUS_TODAY);}catch(e){return new Date().toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'});} })();

  const panel = { background:IC.panel, border:'1px solid '+IC.line, borderRadius:5, overflow:'hidden' };
  const irrColor = irr!=null?(irr>=.18?IC.pos:irr<.12?IC.neg:IC.warn):IC.faint;
  const emColor  = em!=null?(em>=2?IC.pos:em<1.5?IC.neg:IC.warn):IC.faint;

  return (
    <div id="ic-memo-sheet" style={{ width:1200, background:IC.bg, color:IC.navy,
      fontFamily:IC.sans, WebkitFontSmoothing:'antialiased' }}>

      {/* ── HEADER ── */}
      <div style={{ background:IC.navy, padding:'7px 18px 8px', display:'flex',
        alignItems:'center', justifyContent:'space-between', gap:16 }}>
        <div>
          <div style={{ fontSize:9.5, letterSpacing:'.1em', textTransform:'uppercase',
            color:'rgba(255,255,255,.42)', fontWeight:500, marginBottom:2 }}>
            Altus Equity – Investment Committee Memo – Confidential
          </div>
          <div style={{ fontSize:26, fontWeight:700, color:'#fff', lineHeight:1.05,
            marginBottom:3, fontFamily:IC.serif }}>{deal.name||'Untitled Deal'}</div>
          <div style={{ display:'flex', alignItems:'center', whiteSpace:'nowrap',
            fontSize:11, color:'rgba(255,255,255,.62)', fontWeight:500 }}>
            {[deal.market, deal.type,
              deal.units?(deal.units.toLocaleString()+' Units'):null,
              deal.vintage?('Built '+deal.vintage):null]
              .filter(Boolean).map((t,i) => (
              <span key={i}>{i>0&&<span style={{ opacity:.4, margin:'0 7px' }}>•</span>}{t}</span>
            ))}
          </div>
        </div>
        <div style={{ display:'flex', gap:8, alignItems:'center', flexShrink:0 }}>
          <div style={{ display:'inline-flex', alignItems:'center', gap:7,
            border:'1.5px solid '+IC.gold, borderRadius:4, padding:'5px 10px',
            color:IC.gold, fontSize:11, fontWeight:600, letterSpacing:'.02em', whiteSpace:'nowrap' }}>
            <svg width="13" height="13" viewBox="0 0 15 15" fill="none" stroke="currentColor"
              strokeWidth="1.5" strokeLinejoin="round">
              <path d="M7.5 1.5L13 3.5V8.5C13 11.5 10.5 13.6 7.5 14.5C4.5 13.6 2 11.5 2 8.5V3.5Z"/>
              <polyline points="5,7.5 6.5,9 10,5.5"/>
            </svg>
            {statusLabel} – IC Review
          </div>
        </div>
      </div>

      {/* ── METRICS BAR ── */}
      <div style={{ background:IC.panel, borderBottom:'1px solid '+IC.line,
        padding:'4px 10px', display:'flex', gap:8 }}>
        <div style={{ flex:6, border:'1.5px solid '+IC.line, borderRadius:5, padding:'4px 10px 5px' }}>
          <div style={{ fontSize:9, fontWeight:700, letterSpacing:'.1em', textTransform:'uppercase',
            color:IC.blue, marginBottom:3 }}>Deal Metrics</div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(6,1fr)' }}>
            <MetricCell label="Deal IRR"        value={_p(irr)}             color={irrColor} />
            <MetricCell label="Equity Multiple"  value={_x(em)}              color={emColor} />
            <MetricCell label="Yield on Cost"    value={_p(yoc||caps.stab)}  color={IC.blue} />
            <MetricCell label="Going-In Cap"     value={_p(caps.goingIn)} />
            <MetricCell label="Exit Cap Rate"    value={uw?_r(uw.exitCap*100):'—'} />
            <MetricCell label="Hold Period"      value={uw?(uw.hold+' Yrs'):'—'} last />
          </div>
        </div>
        <div style={{ flex:4, border:'1.5px solid '+IC.line, borderRadius:5, padding:'4px 10px 5px' }}>
          <div style={{ fontSize:9, fontWeight:700, letterSpacing:'.1em', textTransform:'uppercase',
            color:IC.blue, marginBottom:3 }}>Loan Terms</div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)' }}>
            <MetricCell label="DSCR (Stab.)" value={dscr!=null?(_n(dscr)+'x'):'—'}
              color={dscr!=null?(dscr>=1.25?IC.pos:dscr<1.1?IC.neg:IC.warn):IC.faint} />
            <MetricCell label="LTV"          value={ltv!=null?_p(ltv):'—'}
              color={ltv!=null?(ltv<=.65?IC.pos:ltv>=.75?IC.neg:IC.warn):IC.faint} />
            <MetricCell label="Interest Rate" value={uw&&uw.acqLoan?((uw.acqLoan.rate*100).toFixed(2)+'%'):'—'} />
            <MetricCell label="Amortization"  value={uw&&uw.acqLoan?(Math.round(uw.acqLoan.amMonths/12)+' Yrs'):'—'} last />
          </div>
        </div>
      </div>

      {/* ── BODY ── */}
      <div style={{ padding:'5px', display:'flex', flexDirection:'column', gap:5 }}>

        {/* TOP ROW */}
        <div style={{ display:'grid', gridTemplateColumns:'270px 1fr', gap:5 }}>

          {/* LEFT COLUMN */}
          <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
            <div style={panel}>
              <PanelHdr>Deal Snapshot</PanelHdr>
              {[
                ['Purchase Price',  _m(deal.purchasePrice)],
                ['CapEx Budget',    _m(deal.capex)],
                ['Total Basis',     _m(basis), true],
                ['Units',           deal.units?deal.units.toLocaleString():'—'],
                ['Year Built',      deal.vintage||'—'],
                ['Current Occ.',   uw?_p(1-uw.inPlaceEconVac,0):'—'],
                ['Econ. Vacancy',  uw?_p(uw.inPlaceEconVac):'—'],
                ['Avg Rent / Mo',  uw&&uw.gpr0&&deal.units?'$'+Math.round(uw.gpr0/deal.units/12).toLocaleString():'—'],
                ['Year-1 NOI',     yr1Row?_m(yr1Row.noi):'—'],
                ['Stabilized NOI', stabRow?_m(stabRow.noi):'—'],
                ['Going-In Cap',   _p(caps.goingIn), false, true],
                ['Yield on Cost',  _p(yoc||caps.stab)],
              ].map(([lbl,val,s,sep])=><DR key={lbl} label={lbl} value={val} strong={!!s} sep={!!sep} />)}
            </div>
            <div style={panel}>
              <PanelHdr>Capital Structure & Financing</PanelHdr>
              <CapDonut uw={uw} basis={basis} />
            </div>
          </div>

          {/* SCENARIO ANALYSIS */}
          <div style={panel}>
            <div style={{ padding:'4px 11px 4px', borderBottom:'1px solid '+IC.line,
              display:'flex', alignItems:'baseline', gap:10 }}>
              <span style={{ fontSize:10, fontWeight:700, letterSpacing:'.08em',
                textTransform:'uppercase', color:IC.navy }}>Scenario Analysis</span>
              <span style={{ fontSize:9.5, color:IC.muted, fontStyle:'italic' }}>
                Average hold-period yield and IRR at the deal and LP level across three cases.
              </span>
            </div>
            <div style={{ padding:'5px 11px 6px' }}>
              <ScenarioAnalysis deal={deal} uw={uw} />
            </div>
          </div>
        </div>

        {/* BOTTOM ROW */}
        <div style={{ display:'grid', gridTemplateColumns:'27fr 31fr 42fr', gap:5 }}>
          <div style={panel}>
            <PanelHdr>Return Decomposition</PanelHdr>
            {uw ? <ReturnDecomp uw={uw} /> :
              <div style={{ padding:'8px 11px', fontSize:9.5, color:IC.faint, fontStyle:'italic' }}>No UW data.</div>}
          </div>
          <div style={panel}>
            <PanelHdr>Underwriting Assumptions</PanelHdr>
            {uw ? <UWAssumptions uw={uw} /> :
              <div style={{ padding:'8px 11px', fontSize:9.5, color:IC.faint, fontStyle:'italic' }}>No UW data.</div>}
          </div>
          <div style={panel}>
            <PanelHdr>Operating Forecast (NOI)</PanelHdr>
            <div style={{ padding:'4px 11px 5px' }}>
              {uw ? <OperatingForecast uw={uw} /> :
                <div style={{ fontSize:9.5, color:IC.faint, fontStyle:'italic' }}>No UW data.</div>}
            </div>
          </div>
        </div>

        {/* OPTIONAL: Thesis / Risks / Market */}
        {((memo.keyStrengths||memo.valueDrivers||memo.keyRisks||memo.risks||[]).length > 0 || mr) && (
          <div style={{ display:'grid',
            gridTemplateColumns: mr ? '1fr 1fr 1fr' : '1fr 1fr', gap:5 }}>
            {(memo.keyStrengths||memo.valueDrivers||[]).length > 0 && (
              <div style={panel}>
                <PanelHdr>Investment Thesis</PanelHdr>
                <div style={{ padding:'5px 11px' }}>
                  {(memo.keyStrengths||memo.valueDrivers||[]).slice(0,4).map((s,i)=><Bul key={i} text={s} tone="pos" />)}
                </div>
              </div>
            )}
            {(memo.keyRisks||memo.risks||[]).length > 0 && (
              <div style={panel}>
                <PanelHdr>Key Risks</PanelHdr>
                <div style={{ padding:'5px 11px' }}>
                  {(memo.keyRisks||memo.risks||[]).slice(0,4).map((r,i)=><Bul key={i} text={r} tone="neg" />)}
                </div>
              </div>
            )}
            {mr && (
              <div style={panel}>
                <PanelHdr>Market Overview</PanelHdr>
                <div style={{ padding:'5px 0' }}>
                  {[['Submarket Grade', mr.grade||mr.submarketContext?.overallGrade||'—'],
                    ['Resident Sentiment', mr.residentSentiment?(mr.residentSentiment.rating+'/5 · '+mr.residentSentiment.trend):(mr.tenantReviews?.rating||'—')],
                    ['Crime Level', mr.crimeSnapshot?.overall?.label||(mr.crime?.level)||'—'],
                  ].map(([lbl,val])=><DR key={lbl} label={lbl} value={val} />)}
                </div>
              </div>
            )}
          </div>
        )}

        {!uw && (
          <div style={{ ...panel, padding:'8px 11px', fontSize:9.5, color:IC.faint, fontStyle:'italic' }}>
            Complete Full Underwriting to populate scenario analysis, operating forecast, and return decomposition.
          </div>
        )}
      </div>

      {/* ── FOOTER ── */}
      <div style={{ borderTop:'1px solid '+IC.line, background:'#f4f6f9', padding:'5px 18px',
        display:'flex', justifyContent:'space-between', fontSize:8.5, color:IC.faint }}>
        <span>Altus Equity — For Investment Committee use only.</span>
        <span>Prepared {todayStr}</span>
      </div>
    </div>
  );
}

// ─── Button + overlay ─────────────────────────────────────────────────────────
function ICMemoButton({ deal, onRunMemo }) {
  const [open, setOpen] = useSIC(false);
  const [busy, setBusy] = useSIC(false);
  const [err,  setErr]  = useSIC(null);
  const hasMemo = deal.memo&&deal.memo.data;

  const openMemo = async () => {
    setOpen(true); setErr(null);
    if (!hasMemo) {
      setBusy(true);
      try   { await onRunMemo(deal.id); }
      catch (e) { setErr(String(e&&e.message?e.message:e)); }
      finally   { setBusy(false); }
    }
  };
  const regen = async () => {
    setBusy(true); setErr(null);
    try   { await onRunMemo(deal.id); }
    catch (e) { setErr(String(e&&e.message?e.message:e)); }
    finally   { setBusy(false); }
  };

  return (
    <React.Fragment>
      <button onClick={openMemo}
        style={{ display:'inline-flex', alignItems:'center', gap:8, border:'none',
          background:'var(--navy)', color:'#fff', borderRadius:9, padding:'10px 16px',
          fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'var(--font)',
          width:'100%', justifyContent:'center' }}>
        <Icon name="doc" size={15} /> Generate IC Memo
      </button>

      {open && (
        <div onClick={(e)=>{ if(e.target===e.currentTarget) setOpen(false); }}
          style={{ position:'fixed', inset:0, zIndex:90, background:'rgba(5,13,22,.68)',
            display:'flex', flexDirection:'column', alignItems:'center',
            padding:'20px 0', overflow:'auto' }}>

          <div className="memo-toolbar" style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14 }}>
            <button onClick={()=>window.print()} disabled={busy}
              style={{ border:'none', background:'var(--accent)', color:'#fff', borderRadius:8,
                padding:'9px 18px', fontSize:13, fontWeight:600, cursor:'pointer',
                fontFamily:'var(--font)', display:'inline-flex', alignItems:'center', gap:7 }}>
              <Icon name="download" size={14} /> Export PDF
            </button>
            <button onClick={regen} disabled={busy}
              style={{ border:'1px solid rgba(255,255,255,.4)', background:'transparent',
                color:'#fff', borderRadius:8, padding:'9px 16px', fontSize:13,
                fontWeight:600, cursor:'pointer', fontFamily:'var(--font)' }}>
              {busy?'Generating…':'Regenerate'}
            </button>
            <button onClick={()=>setOpen(false)}
              style={{ border:'1px solid rgba(255,255,255,.4)', background:'transparent',
                color:'#fff', borderRadius:8, padding:'9px 14px', fontSize:13,
                fontWeight:600, cursor:'pointer', fontFamily:'var(--font)' }}>
              Close
            </button>
          </div>

          {busy && !hasMemo ? (
            <div style={{ background:'#fff', borderRadius:12, padding:60, textAlign:'center',
              width:1200, maxWidth:'94vw', boxSizing:'border-box' }}>
              <div style={{ width:32, height:32, borderRadius:'50%', border:'3px solid var(--accent)',
                borderTopColor:'transparent', animation:'spin .8s linear infinite', margin:'0 auto 14px' }}/>
              <div style={{ fontSize:15, fontWeight:600, color:'var(--ink)' }}>Drafting IC memo…</div>
              <div style={{ fontSize:12.5, color:'var(--muted)', marginTop:6 }}>
                Synthesizing investment thesis, strengths, risks and deal killers.
              </div>
            </div>
          ) : (
            <div style={{ boxShadow:'0 24px 64px rgba(0,0,0,.5)', borderRadius:8,
              overflow:'hidden', maxWidth:'94vw' }}>
              <ICMemoSheet deal={deal} />
            </div>
          )}

          {err && <div style={{ marginTop:12, color:'#ffb4b6', fontSize:13 }}>{err}</div>}
        </div>
      )}
    </React.Fragment>
  );
}

window.ICMemoButton = ICMemoButton;
