// OS Builder — live Build Summary sidebar.
// Sticky right-rail showing what the user has built so far + investment + ROI projection.

function OSBuildSummary({ state, currentPhase, totalPhases, jumpToPhase }) {
  const pricing = osBuilderPricing(state);
  const ident = state.identity || {};
  const tradeName = ident.trades?.length ? TRADES.filter(t => ident.trades.includes(t.id)).map(t => t.name).join(' · ') : '—';
  const revTier   = REVENUE_TIERS.find(r => r.id === ident.revenue)?.label || '—';

  const topPains = (ident.painsRanked || []).slice(0, 3)
    .map(id => PAIN_POINTS.find(p => p.id === id)).filter(Boolean);

  // % progress
  const pct = Math.round((currentPhase / Math.max(1, totalPhases-1)) * 100);

  return (
    <aside style={{
      position:'sticky', top:120, alignSelf:'flex-start',
      width:340, flexShrink:0,
      maxHeight:'calc(100vh - 140px)', overflowY:'auto',
    }}>
      {/* HEADER */}
      <div style={{
        background:'var(--ink)', color:'var(--paper)', borderRadius:'20px 20px 0 0',
        padding:'18px 20px',
      }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:6 }}>
          <span className="eyebrow" style={{ color:'var(--chart-300)' }}>Your Build</span>
          <span style={{ fontFamily:'var(--font-mono)', fontSize:11, color:'var(--chart-200)', opacity:0.7 }}>
            {String(currentPhase+1).padStart(2,'0')} / {String(totalPhases).padStart(2,'0')}
          </span>
        </div>
        <div style={{ fontFamily:'var(--font-display)', fontSize:22, fontWeight:500, letterSpacing:'-0.025em', lineHeight:1.1 }}>
          {ident.bizName || 'Your operating system'}
        </div>
        <div style={{ fontSize:12, color:'var(--chart-200)', opacity:0.75, marginTop:3, fontFamily:'var(--font-mono)' }}>
          {tradeName} · {revTier}
        </div>
        {/* progress bar */}
        <div style={{ marginTop:14, height:4, background:'rgba(255,255,255,0.1)', borderRadius:99, overflow:'hidden' }}>
          <div style={{ width:`${pct}%`, height:'100%', background:'var(--chart-300)', transition:'width .3s ease' }}/>
        </div>
      </div>

      {/* BI SCORE */}
      <div style={{
        background:'linear-gradient(180deg, var(--ink-2) 0%, var(--ink) 100%)',
        color:'var(--paper)', padding:'18px 20px',
        borderBottom:'1px solid rgba(255,255,255,0.06)',
      }}>
        <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between' }}>
          <span style={{ fontSize:10.5, fontWeight:700, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--chart-200)', opacity:0.85 }}>Business Intelligence</span>
          <span style={{ fontFamily:'var(--font-mono)', fontSize:11, color:'var(--mute-3)' }}>0 → 100</span>
        </div>
        <div style={{ display:'flex', alignItems:'baseline', gap:6, marginTop:6 }}>
          <span style={{ fontFamily:'var(--font-display)', fontSize:54, fontWeight:500, letterSpacing:'-0.035em', color:'var(--chart-300)', lineHeight:1 }}>{pricing.bi}</span>
          <span style={{ fontSize:13, color:'var(--mute-2)' }}>/ 100</span>
        </div>
        <div style={{ marginTop:8, height:6, background:'rgba(255,255,255,0.08)', borderRadius:99, overflow:'hidden' }}>
          <div style={{ width:`${pricing.bi}%`, height:'100%', background:'var(--chart-300)', transition:'width .3s ease' }}/>
        </div>
        <div style={{ fontSize:11, color:'var(--mute-3)', marginTop:6, fontFamily:'var(--font-mono)' }}>
          {pricing.bi < 30 ? 'Connect more sources to lift this' : pricing.bi < 60 ? 'Solid foundation forming' : pricing.bi < 85 ? 'Operator-grade visibility' : 'Network-class intelligence'}
        </div>
      </div>

      {/* QUICK COUNTS */}
      <div style={{ background:'var(--paper)', border:'1px solid var(--line)', borderTop:0 }}>
        <SummaryRow label="Data sources connected" value={pricing.connectionCount} accent="lilac" onClick={()=>jumpToPhase(1)}/>
        <SummaryRow label="AI modules active" value={pricing.moduleCount} accent="chart" onClick={()=>jumpToPhase(2)}/>
        <SummaryRow label="Automations on" value={pricing.automationCount} accent="lilac" onClick={()=>jumpToPhase(3)}/>
        <SummaryRow label="Dashboard widgets" value={(state.dashboards?.owner||[]).length} accent="chart" onClick={()=>jumpToPhase(4)} last/>
      </div>

      {/* INVESTMENT */}
      <div style={{ background:'var(--paper-3)', padding:'16px 20px', borderTop:'1px solid var(--line-2)' }}>
        <div style={{ fontSize:10.5, fontWeight:700, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--mute-1)', marginBottom:8 }}>Investment · live</div>
        <PriceRow label="Setup · one-time" value={`$${pricing.setup.toLocaleString()}`} bold/>
        <PriceRow label="Monthly retainer" value={`$${pricing.retainer.toLocaleString()}`} bold/>
        <div style={{ marginTop:10, paddingTop:10, borderTop:'1px solid var(--line)' }}>
          <PriceRow label="Of which · base" value={`$${(pricing.retainer - pricing.moduleMonthly - pricing.autoMonthly).toLocaleString()}`} muted/>
          <PriceRow label="Of which · modules" value={`+$${pricing.moduleMonthly.toLocaleString()}`} muted/>
          <PriceRow label="Of which · automations" value={`+$${pricing.autoMonthly.toLocaleString()}`} muted/>
        </div>
        <div style={{
          marginTop:12, padding:'10px 12px',
          background:'var(--ink)', color:'var(--chart-300)',
          borderRadius:10,
        }}>
          <div style={{ fontSize:10, letterSpacing:'0.1em', textTransform:'uppercase', opacity:0.7, marginBottom:2, fontWeight:600 }}>Success fee</div>
          <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between' }}>
            <span style={{ fontSize:12, color:'var(--paper)' }}>5% on data-proven new revenue</span>
            <span style={{ fontFamily:'var(--font-mono)', fontSize:13, color:'var(--chart-300)' }}>variable</span>
          </div>
        </div>
      </div>

      {/* ROI */}
      <div style={{ background:'var(--chart-100)', padding:'16px 20px', borderTop:'2px solid var(--chart-500)' }}>
        <div style={{ fontSize:10.5, fontWeight:700, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--chart-900)', marginBottom:6 }}>12-Month ROI Projection</div>
        <div style={{ fontFamily:'var(--font-display)', fontSize:30, fontWeight:500, letterSpacing:'-0.03em', color:'var(--ink)', lineHeight:1 }}>
          +${Math.round(pricing.liftDollars/1000)}K
        </div>
        <div style={{ fontSize:11.5, color:'var(--chart-900)', marginTop:5, lineHeight:1.4 }}>
          {Math.round(pricing.liftPct * 100)}% lift on a ${(pricing.revBase/1e6).toFixed(2)}M baseline · benchmarked from similar operators
        </div>
      </div>

      {/* TOP 3 METRICS */}
      {topPains.length > 0 && (
        <div style={{ background:'var(--paper)', padding:'16px 20px', borderTop:'1px solid var(--line)' }}>
          <div style={{ fontSize:10.5, fontWeight:700, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--mute-1)', marginBottom:8 }}>Your top 3 problems · always visible</div>
          <div style={{ display:'flex', flexDirection:'column', gap:7 }}>
            {topPains.map((p, i) => (
              <div key={p.id} style={{ display:'flex', alignItems:'flex-start', gap:8, fontSize:12.5, color:'var(--ink)', lineHeight:1.4 }}>
                <span style={{ fontFamily:'var(--font-mono)', fontSize:10.5, fontWeight:700, color:'var(--lilac-700)', background:'var(--lilac-100)', padding:'1px 6px', borderRadius:99, flexShrink:0, marginTop:2 }}>#{i+1}</span>
                <span>{p.label}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* FOOTER */}
      <div style={{
        background:'var(--paper)', borderRadius:'0 0 20px 20px',
        padding:'14px 20px', borderTop:'1px solid var(--line)',
        fontSize:11, color:'var(--mute-1)', display:'flex', justifyContent:'space-between', alignItems:'center',
      }}>
        <span style={{ fontFamily:'var(--font-mono)' }}>auto-saved</span>
        <span style={{ display:'flex', alignItems:'center', gap:5 }}>
          <span style={{ width:6, height:6, borderRadius:99, background:'var(--chart-500)' }} className="pulse-soft"/>
          live
        </span>
      </div>
    </aside>
  );
}

function SummaryRow({ label, value, accent='chart', onClick, last }) {
  const T = OS_TONES[accent];
  return (
    <button onClick={onClick} type="button" style={{
      display:'flex', alignItems:'center', justifyContent:'space-between',
      width:'100%', padding:'11px 20px',
      background:'transparent', border:0, borderBottom: last ? 0 : '1px solid var(--line-2)',
      cursor:'pointer', textAlign:'left',
    }}>
      <span style={{ fontSize:13, color:'var(--ink)' }}>{label}</span>
      <span style={{
        fontFamily:'var(--font-mono)', fontSize:14, fontWeight:700,
        color: value > 0 ? T.fg : 'var(--mute-2)',
        background: value > 0 ? T.bg : 'transparent',
        padding: value > 0 ? '2px 9px' : 0,
        borderRadius:99,
      }}>{value}</span>
    </button>
  );
}

function PriceRow({ label, value, bold, muted }) {
  return (
    <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', padding:'3px 0' }}>
      <span style={{ fontSize: muted ? 11.5 : 12.5, color: muted ? 'var(--mute-1)' : 'var(--ink)', fontWeight: bold ? 600 : 400 }}>{label}</span>
      <span style={{ fontFamily:'var(--font-mono)', fontSize: muted ? 11.5 : 14, color: muted ? 'var(--mute-1)' : 'var(--ink)', fontWeight: bold ? 700 : 500 }}>{value}</span>
    </div>
  );
}

Object.assign(window, { OSBuildSummary });