// Category marketplace — one component reused across all opportunity
// categories. Reads its catalog from OPP_MARKETPLACES[category].

function MarketplaceScreen({ theme, accent, category, onBack }) {
  const midnight = theme?.label === 'Midnight';
  const config = OPP_MARKETPLACES[category];
  // Default ordering (best match) is applied silently; there is no sort UI.
  const defaultCmp = (config && config.sorts && config.sorts[0] && config.sorts[0].cmp) || ((a, b) => (b.aiScore ?? 0) - (a.aiScore ?? 0));
  const filterDefs = (config && config.filters) || [];
  const [eligibleOnly, setEligibleOnly] = React.useState(true);
  const [active, setActive] = React.useState(() => ({})); // category filter key -> bool
  const [applyProduct, setApplyProduct] = React.useState(null);

  if (!config) {
    return (
      <Screen theme={theme} padTop={0} padBottom={48}>
        <InsightDetailNav theme={theme} label="Marketplace" onBack={onBack} />
        <div style={{ padding: '20px 16px', fontFamily: FONTS.ui, fontSize: 13, color: theme.textDim }}>
          This marketplace is not available yet.
        </div>
      </Screen>
    );
  }

  const activeFilterDefs = filterDefs.filter((f) => active[f.key]);
  const passesFilters = (p) =>
    (!eligibleOnly || p.eligible) && activeFilterDefs.every((f) => f.test(p));
  const visible = [...config.products].filter(passesFilters).sort(defaultCmp);
  const eligibleAlternatives = config.products.filter((p) => p.eligible && !p.isCurrent);
  const toggleFilter = (key) => setActive((a) => ({ ...a, [key]: !a[key] }));
  const clearAll = () => { setActive({}); setEligibleOnly(true); };

  const chip = (label, isActive, onClick, leading) => (
    <button key={label} onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0,
      padding: '7px 12px', borderRadius: 999, cursor: 'pointer', whiteSpace: 'nowrap',
      background: isActive ? `${accent}14` : 'transparent',
      border: `1px solid ${isActive ? `${accent}55` : theme.line2}`,
      color: isActive ? accent : theme.textDim,
      fontFamily: FONTS.ui, fontSize: 12, fontWeight: 600, transition: 'background 140ms',
    }}>
      {leading}
      {label}
    </button>
  );

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

          {/* Filter chips — eligibility + category-relevant toggles */}
          <div style={{ display: 'flex', gap: 7, overflowX: 'auto', margin: '0 -16px', padding: '0 16px 2px' }}>
            {chip(
              'Eligible for me',
              eligibleOnly,
              () => setEligibleOnly((v) => !v),
              <Ico.check size={12} sw={2.4} style={{ color: eligibleOnly ? accent : theme.textMute }} />,
            )}
            {filterDefs.map((f) => chip(f.label, !!active[f.key], () => toggleFilter(f.key)))}
          </div>

          {/* Empty state */}
          {visible.length === 0 && (
            <div style={{ textAlign: 'center', padding: '28px 16px' }}>
              <div style={{ fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 600, color: theme.text }}>No products match these filters</div>
              <button onClick={clearAll} style={{
                marginTop: 12, background: 'transparent', color: accent,
                border: `1.5px solid ${accent}30`, borderRadius: 999, padding: '9px 18px',
                fontFamily: FONTS.ui, fontSize: 13, fontWeight: 600, cursor: 'pointer',
              }}>Clear filters</button>
            </div>
          )}

          {/* Product cards */}
          {visible.map((p) => {
            const grey = !p.eligible;
            return (
              <div key={p.id} style={{
                background: midnight ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.78)',
                border: midnight ? '0.5px solid rgba(255,255,255,0.08)' : 'none',
                borderRadius: 18, padding: '16px 16px',
                boxShadow: midnight ? 'none' : '0 2px 14px rgba(0,0,0,0.05)',
                opacity: grey ? 0.55 : 1,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <BrandLogo name={p.provider} size={36} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    {/* Name gets the full width of this column — never truncated */}
                    <div style={{ fontFamily: FONTS.ui, fontSize: 14, fontWeight: 600, color: theme.text, lineHeight: 1.25 }}>{p.name}</div>
                    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10, marginTop: 3 }}>
                      <span style={{ flex: 1, minWidth: 0, fontFamily: FONTS.ui, fontSize: 11.5, color: theme.textDim, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{dhText(p.sub || p.rateSummary || '')}</span>
                      {(p.metricValue != null || p.net12m != null) && (
                        <span style={{ flexShrink: 0, fontFamily: FONTS.mono, fontSize: 12.5, fontWeight: 600, color: grey ? theme.textDim : accent }}>
                          {dhText(p.metricValue != null ? p.metricValue : `AED ${p.net12m.toLocaleString()}`)}
                          <span style={{ fontFamily: FONTS.mono, fontSize: 8.5, color: theme.textMute, textTransform: 'uppercase', letterSpacing: 0.4, marginLeft: 5 }}>{p.metricLabel || 'est. net/yr'}</span>
                        </span>
                      )}
                    </div>
                  </div>
                </div>

                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 11 }}>
                  {p.isCurrent && (
                    <span style={{ fontFamily: FONTS.mono, fontSize: 9, color: theme.textMute, background: theme.surface3, padding: '4px 9px', borderRadius: 999, letterSpacing: 0.4, textTransform: 'uppercase' }}>{p.currentTag || 'Your card'}</span>
                  )}
                  {!grey && !p.isCurrent && p.aiScore >= 85 && (
                    <span style={{ fontFamily: FONTS.mono, fontSize: 9, color: accent, background: `${accent}14`, padding: '4px 9px', borderRadius: 999, letterSpacing: 0.4, textTransform: 'uppercase' }}>Top match</span>
                  )}
                  {(p.chips || [
                    p.annualFee === 0 ? 'No annual fee' : `Fee · AED ${(p.annualFee || 0).toLocaleString()}/yr`,
                    ...(p.perks || []).slice(0, 2),
                  ]).map((chip) => (
                    <span key={chip} style={{ fontFamily: FONTS.mono, fontSize: 9.5, color: theme.textDim, background: theme.surface2, border: `0.5px solid ${theme.line2}`, borderRadius: 999, padding: '4px 10px' }}>{dhText(chip)}</span>
                  ))}
                </div>

                {grey ? (
                  <div style={{ fontFamily: FONTS.ui, fontSize: 11.5, color: theme.warning, marginTop: 12 }}>
                    {p.eligibilityNote}
                  </div>
                ) : (p.isCurrent && !p.applyable) ? (
                  <div style={{ fontFamily: FONTS.ui, fontSize: 11.5, color: theme.textMute, marginTop: 12 }}>
                    {p.currentNote || 'This is what you have today.'}
                  </div>
                ) : (
                  <button onClick={() => setApplyProduct(p)} style={{
                    width: '100%', marginTop: 13, background: 'transparent', color: accent,
                    border: `1.5px solid ${accent}30`, borderRadius: 12, padding: '10px 0',
                    fontFamily: FONTS.ui, fontSize: 13, fontWeight: 600, cursor: 'pointer',
                  }}>
                    Apply
                  </button>
                )}
              </div>
            );
          })}

          <div style={{ fontFamily: FONTS.ui, fontSize: 10.5, color: theme.textMute, lineHeight: 1.5, padding: '4px 4px 0' }}>
            {OPP_DISCLAIMER}
          </div>
        </div>
      </Screen>

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

Object.assign(window, { MarketplaceScreen });
