// Shared opportunity components: partner application flow + assumptions footer.
// One PartnerApplySheet parameterized by product, reused by all 9 opportunity
// screens and the marketplace. Visual language matches insight_flows.jsx.

// ── Assumptions & disclaimer footer (collapsible) ────────────────────────────
function OppAssumptions({ theme, assumptions }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ padding: '4px 4px 0' }}>
      <button onClick={() => setOpen((v) => !v)} style={{
        display: 'flex', alignItems: 'center', gap: 6, background: 'transparent',
        border: 'none', padding: 0, cursor: 'pointer',
        fontFamily: FONTS.ui, fontSize: 12, fontWeight: 600, color: theme.textDim,
      }}>
        <Ico.info size={12} />
        How we calculated this
        <Ico.chevD size={11} style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 160ms' }} />
      </button>
      {open && (
        <div style={{ marginTop: 10 }}>
          {(assumptions || []).map((a, i) => (
            <div key={i} style={{ display: 'flex', gap: 8, padding: '4px 0' }}>
              <span style={{ width: 4, height: 4, borderRadius: 2, background: theme.textMute, flexShrink: 0, marginTop: 7 }} />
              <span style={{ fontFamily: FONTS.ui, fontSize: 11.5, color: theme.textDim, lineHeight: 1.5 }}>{a}</span>
            </div>
          ))}
        </div>
      )}
      <div style={{ fontFamily: FONTS.ui, fontSize: 10.5, color: theme.textMute, lineHeight: 1.5, marginTop: 10 }}>
        {OPP_DISCLAIMER}
      </div>
    </div>
  );
}

// ── Partner application flow ──────────────────────────────────────────────────
// product: { name, provider, keyTerms: [[k,v],...], eligible, eligibilityNote }
// alternatives: eligible products shown on a soft decline
function PartnerApplySheet({ theme, accent, product, alternatives, onClose, onExploreAll }) {
  const midnight = theme?.label === 'Midnight';
  const sheetBg = midnight ? '#1B1F2E' : '#FFFFFF';
  const [step, setStep] = React.useState('summary'); // summary → consent → checking → result → done
  const [consented, setConsented] = React.useState(false);
  const prequalified = product.eligible !== false;

  React.useEffect(() => {
    if (step !== 'checking') return;
    const t = setTimeout(() => setStep('result'), 1600);
    return () => clearTimeout(t);
  }, [step]);

  const label = (text) => (
    <div style={{ fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1.3, textTransform: 'uppercase', color: theme.textMute, margin: '18px 0 10px' }}>{text}</div>
  );
  const primaryBtn = (text, onClick, disabled) => (
    <button onClick={onClick} disabled={disabled} style={{
      width: '100%', marginTop: 20, background: disabled ? theme.surface3 : accent,
      color: disabled ? theme.textMute : onAccent(accent), border: 'none',
      borderRadius: 16, padding: '15px 20px', fontFamily: FONTS.ui, fontSize: 15,
      fontWeight: 600, cursor: disabled ? 'default' : 'pointer', letterSpacing: -0.2,
    }}>{text}</button>
  );
  const row = (k, v, i, arr) => (
    <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '9px 0', borderBottom: i < arr.length - 1 ? `0.5px solid ${theme.line2}` : 'none' }}>
      <span style={{ fontFamily: FONTS.ui, fontSize: 12.5, color: theme.textDim, flexShrink: 0 }}>{k}</span>
      <span style={{ fontFamily: FONTS.ui, fontSize: 12.5, fontWeight: 500, color: theme.text, textAlign: 'right' }}>{dhText(String(v))}</span>
    </div>
  );

  const profileRows = [
    ['Name', OPP_PROFILE.fullName],
    ['Emirates ID', OPP_PROFILE.emiratesId],
    ['Monthly income', `AED ${OPP_PROFILE.monthlyIncome.toLocaleString()}`],
    ['Employer', OPP_PROFILE.employer],
  ];

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 60, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.38)', backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)' }} />
      <div style={{ position: 'relative', zIndex: 1, background: sheetBg, borderRadius: '24px 24px 0 0', boxShadow: '0 -8px 40px rgba(0,0,0,0.18)', maxHeight: '92%', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: midnight ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.12)', margin: '10px auto 0', flexShrink: 0 }} />
        <div style={{ overflowY: 'auto', padding: '16px 20px 28px' }}>

          {/* 1 · Pre-filled summary */}
          {step === 'summary' && (
            <>
              <div style={{ fontFamily: FONTS.display, fontSize: 20, color: theme.text, letterSpacing: -0.4 }}>Apply for {product.name}</div>
              <div style={{ fontFamily: FONTS.ui, fontSize: 12, color: theme.textDim, marginTop: 4 }}>
                {product.provider} · powered by {OPP_PARTNER.name}
              </div>

              {label('Product terms')}
              {(product.keyTerms || []).map(([k, v], i, arr) => row(k, v, i, arr))}

              {label('Your details · pre-filled from Himma')}
              {profileRows.map(([k, v], i, arr) => row(k, v, i, arr))}

              <div style={{ fontFamily: FONTS.ui, fontSize: 11, color: theme.textMute, lineHeight: 1.5, marginTop: 14 }}>
                {OPP_PARTNER.blurb}
              </div>
              {primaryBtn('Continue', () => setStep('consent'))}
            </>
          )}

          {/* 2 · Consent */}
          {step === 'consent' && (
            <>
              <div style={{ fontFamily: FONTS.display, fontSize: 20, color: theme.text, letterSpacing: -0.4 }}>Share your details</div>
              <div style={{ fontFamily: FONTS.ui, fontSize: 12.5, color: theme.textDim, marginTop: 4, lineHeight: 1.5 }}>
                To check eligibility, {OPP_PARTNER.name} and {product.provider} need:
              </div>
              {label('What gets shared')}
              {OPP_CONSENT_ITEMS.map((c, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '6px 0' }}>
                  <span style={{ width: 18, height: 18, borderRadius: 9, background: `${accent}14`, color: accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>
                    <Ico.check size={10} sw={2.4} />
                  </span>
                  <span style={{ fontFamily: FONTS.ui, fontSize: 12.5, color: theme.textDim, lineHeight: 1.45 }}>{c}</span>
                </div>
              ))}
              <button onClick={() => setConsented((v) => !v)} style={{
                width: '100%', display: 'flex', alignItems: 'flex-start', gap: 10, textAlign: 'left',
                background: 'transparent', border: `0.5px solid ${theme.line2}`, borderRadius: 12,
                padding: '12px 12px', marginTop: 16, cursor: 'pointer',
              }}>
                <span style={{
                  width: 20, height: 20, borderRadius: 6, flexShrink: 0,
                  border: consented ? 'none' : `1.5px solid ${theme.line2}`,
                  background: consented ? accent : 'transparent',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {consented && <Ico.check size={12} stroke={onAccent(accent)} sw={2.6} />}
                </span>
                <span style={{ fontFamily: FONTS.ui, fontSize: 12, color: theme.textDim, lineHeight: 1.45 }}>
                  I agree to share these details with {OPP_PARTNER.name} and {product.provider} for this application. I can withdraw consent anytime in Settings.
                </span>
              </button>
              {primaryBtn('Agree & check eligibility', () => setStep('checking'), !consented)}
            </>
          )}

          {/* 3 · Eligibility check (simulated) */}
          {step === 'checking' && (
            <div style={{ textAlign: 'center', padding: '34px 0 30px' }}>
              <div style={{
                width: 44, height: 44, margin: '0 auto 18px', borderRadius: 22,
                border: `3px solid ${accent}22`, borderTopColor: accent,
                animation: 'oppspin 0.9s linear infinite',
              }} />
              <style>{'@keyframes oppspin { to { transform: rotate(360deg); } }'}</style>
              <div style={{ fontFamily: FONTS.display, fontSize: 18, color: theme.text, letterSpacing: -0.3 }}>Checking eligibility</div>
              <div style={{ fontFamily: FONTS.ui, fontSize: 12.5, color: theme.textDim, marginTop: 6 }}>
                {OPP_PARTNER.name} is running a soft check. No credit footprint.
              </div>
            </div>
          )}

          {/* 4 · Result */}
          {step === 'result' && prequalified && (
            <>
              <div style={{ width: 52, height: 52, borderRadius: 26, background: `${theme.positive}14`, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '8px auto 14px' }}>
                <Ico.check size={24} stroke={theme.positive} sw={2.4} />
              </div>
              <div style={{ fontFamily: FONTS.display, fontSize: 20, color: theme.text, letterSpacing: -0.4, textAlign: 'center' }}>You're pre-qualified</div>
              <div style={{ fontFamily: FONTS.ui, fontSize: 12.5, color: theme.textDim, marginTop: 6, textAlign: 'center', lineHeight: 1.5 }}>
                Indicative terms below. Final approval rests with {product.provider}.
              </div>
              {label('Indicative terms')}
              {(product.keyTerms || []).map(([k, v], i, arr) => row(k, v, i, arr))}
              {primaryBtn(`Continue with ${product.provider}`, () => setStep('done'))}
            </>
          )}
          {step === 'result' && !prequalified && (
            <>
              <div style={{ width: 52, height: 52, borderRadius: 26, background: `${theme.warning}14`, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '8px auto 14px' }}>
                <Ico.alert size={24} stroke={theme.warning} sw={2} />
              </div>
              <div style={{ fontFamily: FONTS.display, fontSize: 20, color: theme.text, letterSpacing: -0.4, textAlign: 'center' }}>Not a match right now</div>
              <div style={{ fontFamily: FONTS.ui, fontSize: 12.5, color: theme.textDim, marginTop: 6, textAlign: 'center', lineHeight: 1.5 }}>
                {product.eligibilityNote || 'This product has requirements your profile does not meet yet.'}
              </div>
              {alternatives && alternatives.length > 0 && (
                <>
                  {label('Options you qualify for')}
                  {alternatives.slice(0, 2).map((alt, i, arr) => (
                    <div key={alt.id || alt.name} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '10px 0', borderBottom: i < arr.length - 1 ? `0.5px solid ${theme.line2}` : 'none' }}>
                      <BrandLogo name={alt.provider} size={30} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontFamily: FONTS.ui, fontSize: 13, color: theme.text }}>{alt.name}</div>
                        <div style={{ fontFamily: FONTS.ui, fontSize: 11, color: theme.textDim, marginTop: 1 }}>{dhText(alt.rateSummary || '')}</div>
                      </div>
                    </div>
                  ))}
                </>
              )}
              {primaryBtn('Explore all options', () => { onClose(); if (onExploreAll) onExploreAll(); })}
            </>
          )}

          {/* 5 · Handoff / confirmation */}
          {step === 'done' && (
            <div style={{ textAlign: 'center', padding: '10px 0 4px' }}>
              <div style={{ width: 56, height: 56, borderRadius: 28, background: `${accent}15`, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
                <Ico.send size={24} stroke={accent} sw={1.8} />
              </div>
              <div style={{ fontFamily: FONTS.display, fontSize: 21, color: theme.text, letterSpacing: -0.4 }}>Application started</div>
              <div style={{ fontFamily: FONTS.ui, fontSize: 13, color: theme.textDim, lineHeight: 1.55, margin: '10px auto 0', maxWidth: 280 }}>
                {OPP_PARTNER.name} has passed your application to {product.provider}. We'll track it and update you here.
              </div>
              <div style={{ textAlign: 'left', background: midnight ? 'rgba(255,255,255,0.05)' : theme.surface2, borderRadius: 14, padding: '12px 14px', marginTop: 18 }}>
                {[
                  [`${product.provider} reviews your application`, '1 to 2 business days'],
                  ['You may be asked for documents', 'Salary certificate or bank statement'],
                  ['Track progress in Himma', 'Home · Activity tracker'],
                ].map(([t, s], i) => (
                  <div key={t} style={{ display: 'flex', gap: 11, padding: '7px 0' }}>
                    <span style={{ width: 20, height: 20, borderRadius: 10, background: `${accent}14`, color: accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontFamily: FONTS.mono, fontSize: 10, fontWeight: 700 }}>{i + 1}</span>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontFamily: FONTS.ui, fontSize: 12.5, fontWeight: 550, color: theme.text }}>{t}</div>
                      <div style={{ fontFamily: FONTS.ui, fontSize: 11, color: theme.textDim, marginTop: 1 }}>{s}</div>
                    </div>
                  </div>
                ))}
              </div>
              {primaryBtn('Done', onClose)}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Tap-to-expand disclosure (collapsed detail behind a toggle) ──────────────
function OppDisclosure({ theme, accent, label, children }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ marginTop: 10 }}>
      <button onClick={() => setOpen((v) => !v)} style={{
        display: 'flex', alignItems: 'center', gap: 6, background: 'transparent',
        border: 'none', padding: 0, cursor: 'pointer',
        fontFamily: FONTS.ui, fontSize: 12, fontWeight: 600, color: accent,
      }}>
        {label}
        <Ico.chevD size={11} style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 160ms' }} />
      </button>
      {open && <div style={{ marginTop: 8 }}>{children}</div>}
    </div>
  );
}

// ── Collapsible "why it matters" row: title always shown, body behind a tap ──
function OppWhyItem({ theme, accent, title, body, last }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ borderBottom: last ? 'none' : `0.5px solid ${theme.line2}` }}>
      <button onClick={() => setOpen((v) => !v)} style={{
        width: '100%', textAlign: 'left', cursor: 'pointer', background: 'transparent', border: 'none',
        display: 'flex', alignItems: 'center', gap: 11, padding: '11px 0',
      }}>
        <span style={{ width: 20, height: 20, borderRadius: 10, background: `${accent}14`, color: accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Ico.check size={11} sw={2.4} />
        </span>
        <span style={{ flex: 1, fontFamily: FONTS.ui, fontSize: 13, fontWeight: 600, color: theme.text }}>{title}</span>
        <Ico.chevD size={13} stroke={theme.textMute} sw={1.8} style={{ flexShrink: 0, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 160ms' }} />
      </button>
      {open && (
        <div style={{ fontFamily: FONTS.ui, fontSize: 12, color: theme.textDim, lineHeight: 1.45, padding: '0 0 11px 31px' }}>{body}</div>
      )}
    </div>
  );
}

// ── Generic opportunity detail screen ────────────────────────────────────────
// Renders the shared skeleton (hero → situation → AI reco with Apply CTAs →
// comparison → assumptions → marketplace CTA) from an OPPORTUNITIES entry.
// Card rewards keeps its own bespoke screen; the other 8 use this.
function OpportunityDetailScreen({ theme, accent, onBack, onAskHimma, onNav, opp }) {
  const [applyProduct, setApplyProduct] = React.useState(null);
  const [reminderSet, setReminderSet] = React.useState(false);
  const products = OPP_MARKETPLACES[opp.category].products;
  const alternatives = products.filter((p) => p.eligible && !p.isCurrent);
  const openMarketplace = () => onNav && onNav('marketplace', { category: opp.category, returnTo: opp.route });

  return (
    <div style={{ position: 'relative', height: '100%' }}>
      <Screen theme={theme} padTop={0} padBottom={48}>
        <InsightDetailNav theme={theme} label={opp.navLabel} onBack={onBack} />
        <div style={{ padding: '8px 16px 0', display: 'flex', flexDirection: 'column', gap: 14 }}>

          {/* 1 · Hero — stat hero by default, or a gap hero (icon + context rows) */}
          {opp.gapHero ? (
            <FlowGapHero theme={theme} accent={accent}
              icon={opp.gapHero.icon} title={opp.gapHero.title}
              subtitle={opp.gapHero.subtitle} rows={opp.gapHero.rows} />
          ) : (
            <FlowStatHero theme={theme} accent={accent}
              label={opp.hero.label}
              value={opp.hero.value} prefixDh={opp.hero.dh}
              subtitle={opp.hero.subtitle} info={opp.hero.info}>
              {opp.hero.twoStat && (
                <FlowHighlight theme={theme} accent={accent}>
                  <FlowTwoStat theme={theme} accent={accent}
                    leftLabel={opp.hero.twoStat.leftLabel} leftValue={opp.hero.twoStat.leftValue}
                    rightLabel={opp.hero.twoStat.rightLabel} rightValue={opp.hero.twoStat.rightValue} />
                </FlowHighlight>
              )}
            </FlowStatHero>
          )}

          {/* 2a · Why this matters (optional check-bullet rationale) */}
          {opp.why && (
            <FlowCard theme={theme} label={opp.whyLabel || 'Why it matters'}>
              {opp.why.map(([t, b], i, arr) => (
                opp.whyCollapsible ? (
                  <OppWhyItem key={t} theme={theme} accent={accent} title={t} body={dhText(b)} last={i === arr.length - 1} />
                ) : (
                <div key={t} style={{ display: 'flex', gap: 11, alignItems: 'flex-start', padding: '8px 0', borderBottom: i < arr.length - 1 ? `0.5px solid ${theme.line2}` : 'none' }}>
                  <span style={{ width: 20, height: 20, borderRadius: 10, background: `${accent}14`, color: accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>
                    <Ico.check size={11} sw={2.4} />
                  </span>
                  <div>
                    <div style={{ fontFamily: FONTS.ui, fontSize: 13, fontWeight: 600, color: theme.text }}>{t}</div>
                    <div style={{ fontFamily: FONTS.ui, fontSize: 12, color: theme.textDim, lineHeight: 1.45, marginTop: 2 }}>{dhText(b)}</div>
                  </div>
                </div>
                )
              ))}
            </FlowCard>
          )}

          {/* 2b · Your situation (optional) */}
          {opp.situation && (
          <FlowCard theme={theme} label="Your situation">
            {opp.situation.intro && (
              <div style={{ fontFamily: FONTS.ui, fontSize: 12.5, color: theme.textDim, lineHeight: 1.5, paddingBottom: 6 }}>
                {dhText(opp.situation.intro)}
              </div>
            )}
            {(opp.situation.rows || []).map(([k, v], i, arr) => (
              <FlowRow key={k} theme={theme} accent={accent} label={k} value={dhText(v)}
                last={i === arr.length - 1 && !opp.situation.note && !opp.reminder} />
            ))}
            {opp.situation.valueHeader && (opp.situation.optionRows || []).length > 0 && (
              <div style={{ display: 'flex', paddingBottom: 7, borderBottom: `0.5px solid ${theme.line2}` }}>
                <span style={{ flex: 1 }} />
                <span style={{ fontFamily: FONTS.mono, fontSize: 8.5, color: theme.textMute, letterSpacing: 0.5, textTransform: 'uppercase', textAlign: 'right' }}>{opp.situation.valueHeader}</span>
              </div>
            )}
            {(opp.situation.optionRows || []).map((r, i, arr) => (
              <FlowOptionRow key={r.name} theme={theme} accent={accent}
                name={r.name} sub={dhText(r.sub)} value={dhText(r.value)} valueSub={r.valueSub}
                last={i === arr.length - 1 && !opp.situation.note && !opp.reminder} />
            ))}
            {opp.situation.note && (
              typeof opp.situation.note === 'string' ? (
                <div style={{ fontFamily: FONTS.ui, fontSize: 11.5, color: theme.textDim, lineHeight: 1.55, paddingTop: 10 }}>
                  {dhText(opp.situation.note)}
                </div>
              ) : (
                <OppDisclosure theme={theme} accent={accent} label={opp.situation.note.label}>
                  <div style={{ fontFamily: FONTS.ui, fontSize: 11.5, color: theme.textDim, lineHeight: 1.55 }}>
                    {dhText(opp.situation.note.body)}
                  </div>
                </OppDisclosure>
              )
            )}
            {opp.reminder && (
              <button onClick={() => setReminderSet(true)} disabled={reminderSet} style={{
                width: '100%', marginTop: 12,
                background: reminderSet ? `${theme.positive}14` : 'transparent',
                color: reminderSet ? theme.positive : accent,
                border: reminderSet ? 'none' : `1.5px solid ${accent}30`,
                borderRadius: 12, padding: '10px 0',
                fontFamily: FONTS.ui, fontSize: 13, fontWeight: 600,
                cursor: reminderSet ? 'default' : 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
              }}>
                {reminderSet ? <Ico.check size={13} sw={2.4} /> : <Ico.bell size={13} sw={1.8} />}
                {reminderSet ? opp.reminder.confirm : opp.reminder.label}
              </button>
            )}
          </FlowCard>
          )}

          {/* 3 · AI recommendation with Apply CTAs */}
          <FlowCard theme={theme} label={opp.recoLabel || 'Recommended · Himma AI'}>
            {opp.reco.map((item, i) => {
              const product = products.find((p) => p.id === item.productId);
              return (
                <div key={item.productId} style={{ padding: '12px 0', borderBottom: i < opp.reco.length - 1 ? `0.5px solid ${theme.line2}` : 'none' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                    <BrandLogo name={product.provider} size={32} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 600, color: theme.text }}>{product.name}</div>
                      {!opp.recoHideSub && product.sub && (
                        <div style={{ fontFamily: FONTS.ui, fontSize: 11, color: theme.textDim, marginTop: 2 }}>{dhText(product.sub)}</div>
                      )}
                    </div>
                    {product.metricValue && (
                      <span style={{ fontFamily: FONTS.mono, fontSize: 12, fontWeight: 600, color: accent, flexShrink: 0 }}>
                        {dhText(product.metricValue)}
                      </span>
                    )}
                  </div>
                  {item.tags && (
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 9 }}>
                      {item.tags.map((t) => (
                        <span key={t} style={{ fontFamily: FONTS.mono, fontSize: 9, color: accent, background: `${accent}12`, padding: '3px 9px', borderRadius: 6, letterSpacing: 0.3 }}>{dhText(t)}</span>
                      ))}
                    </div>
                  )}
                  {item.why && (
                    <div style={{ fontFamily: FONTS.ui, fontSize: 11.5, color: theme.textDim, lineHeight: 1.5, marginTop: 8,
                      ...(opp.recoClampWhy ? { display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' } : {}) }}>
                      {dhText(item.why)}
                    </div>
                  )}
                  {item.detail && (
                    <OppDisclosure theme={theme} accent={accent} label={item.detailLabel || 'See details'}>
                      <div style={{ fontFamily: FONTS.ui, fontSize: 11.5, color: theme.textDim, lineHeight: 1.5 }}>
                        {dhText(item.detail)}
                      </div>
                    </OppDisclosure>
                  )}
                  {!item.keep && (
                    <button onClick={() => setApplyProduct(product)} style={{
                      width: '100%', marginTop: 11, background: i === 0 ? accent : 'transparent',
                      color: i === 0 ? onAccent(accent) : accent,
                      border: i === 0 ? 'none' : `1.5px solid ${accent}30`,
                      borderRadius: 12, padding: '10px 0',
                      fontFamily: FONTS.ui, fontSize: 13, fontWeight: 600, cursor: 'pointer',
                    }}>
                      Apply for {product.name}
                    </button>
                  )}
                </div>
              );
            })}
          </FlowCard>

          {/* 4 · Comparison */}
          {opp.compare && (
            <FlowCard theme={theme} label={opp.compare.label}>
              <div style={{ display: 'flex', paddingBottom: 7, borderBottom: `0.5px solid ${theme.line2}` }}>
                <span style={{ flex: 1 }} />
                {opp.compare.columns.map((c) => (
                  <span key={c} style={{ fontFamily: FONTS.mono, fontSize: 8.5, color: theme.textMute, letterSpacing: 0.5, textTransform: 'uppercase', width: 86, textAlign: 'right' }}>{c}</span>
                ))}
              </div>
              {opp.compare.rows.map((r, i) => {
                // Long word-values (e.g. "Comprehensive") overflow the fixed column
                // and collide; drop their size a step so each stays inside its cell.
                const vFont = (String(r.a).length > 9 || String(r.b).length > 9) ? 10 : 11.5;
                return (
                <div key={r.label} style={{ display: 'flex', alignItems: 'center', padding: '9px 0', borderBottom: (i < opp.compare.rows.length - 1 || opp.compare.totals) ? `0.5px solid ${theme.line2}` : 'none' }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontFamily: FONTS.ui, fontSize: 12.5, color: theme.text }}>{r.label}</div>
                    {r.sub && <div style={{ fontFamily: FONTS.ui, fontSize: 10.5, color: theme.textDim, marginTop: 1 }}>{dhText(r.sub)}</div>}
                  </div>
                  <span style={{ fontFamily: FONTS.mono, fontSize: vFont, color: theme.textDim, width: 86, textAlign: 'right', whiteSpace: 'nowrap' }}>{dhText(r.a)}</span>
                  <span style={{ fontFamily: FONTS.mono, fontSize: vFont, fontWeight: r.hi ? 650 : 400, color: r.hi ? accent : theme.text, width: 86, textAlign: 'right', whiteSpace: 'nowrap' }}>{dhText(r.b)}</span>
                </div>
                );
              })}
              {opp.compare.totals && (
                <div style={{ display: 'flex', alignItems: 'center', padding: '10px 0 2px' }}>
                  <span style={{ flex: 1, fontFamily: FONTS.ui, fontSize: 13, fontWeight: 600, color: theme.text }}>{opp.compare.totals.label}</span>
                  <span style={{ fontFamily: FONTS.mono, fontSize: 12, fontWeight: 600, color: theme.text, width: 86, textAlign: 'right' }}>{dhText(opp.compare.totals.a)}</span>
                  <span style={{ fontFamily: FONTS.mono, fontSize: 12, fontWeight: 700, color: accent, width: 86, textAlign: 'right' }}>{dhText(opp.compare.totals.b)}</span>
                </div>
              )}
              {opp.compare.footnote && (
                <div style={{ fontFamily: FONTS.ui, fontSize: 11, color: theme.textDim, lineHeight: 1.5, marginTop: 8 }}>
                  {dhText(opp.compare.footnote)}
                </div>
              )}
            </FlowCard>
          )}

          {/* 5 · Assumptions & disclaimer */}
          <OppAssumptions theme={theme} assumptions={opp.assumptions} />

        </div>
        <FlowCTAs theme={theme} accent={accent}
          primary={opp.exploreLabel}
          secondary="Ask Himma about this"
          onPrimary={openMarketplace} onSecondary={onAskHimma}
        />
      </Screen>

      {applyProduct && (
        <PartnerApplySheet
          theme={theme} accent={accent}
          product={applyProduct}
          alternatives={alternatives.filter((p) => p.id !== applyProduct.id)}
          onClose={() => setApplyProduct(null)}
          onExploreAll={openMarketplace}
        />
      )}
    </div>
  );
}

Object.assign(window, { OppAssumptions, PartnerApplySheet, OpportunityDetailScreen });
