// Read-only dry-run result: elimination funnel + matched tickers. No cost.
// Friendly labels for funnel rejected_by keys (mirrors FILTER_LABELS in
// apps/api/tradingagents/screener/filters.py). Unknown keys fall back to the raw key.
const FUNNEL_FILTER_LABELS = {
  ytd_return_max: 'YTD return', pct_of_6mo_high_max: '% of 6-mo high',
  z_score_5d_max: '5-day z-score', ev_ebitda_min: 'EV/EBITDA min', ev_ebitda_max: 'EV/EBITDA max',
  pe_min: 'P/E min', pe_max: 'P/E max', pb_min: 'P/B min', pb_max: 'P/B max',
  debt_equity_max: 'Debt/Equity max', roe_min: 'ROE min',
  dividend_yield_min: 'Dividend yield min', dividend_yield_max: 'Dividend yield max',
  fcf_positive: 'FCF positive', market_cap: 'Market cap', price_filters: 'Price filters',
};

window.StrategyPreviewModal = function StrategyPreviewModal({ result, loading, error, onClose }) {
  const funnel = result?.funnel;
  return (
    <div onClick={(e) => { if (e.target === e.currentTarget) onClose(); }} style={{
      position: 'fixed', inset: 0, zIndex: 60, background: 'rgba(10,22,40,0.45)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div style={{ width: 620, maxWidth: '92vw', maxHeight: '88vh', overflowY: 'auto',
        background: 'var(--paper)', borderRadius: 14, border: '1px solid var(--ink-150)',
        boxShadow: '0 24px 60px rgba(10,22,40,0.22)', padding: 22 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <div style={{ fontSize: 14, fontWeight: 700 }}>Screener preview (dry run — no analyses queued)</div>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', fontSize: 18 }}>×</button>
        </div>

        {loading && <div style={{ color: 'var(--ink-500)' }}>Running screen… (universe may take up to ~2 min)</div>}
        {error && <window.ErrorBanner error={{ message: error }}/>}

        {funnel && (
          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-500)', marginBottom: 8 }}>Elimination funnel</div>
            <div style={{ fontSize: 13 }}>Universe: <b>{funnel.universe_count}</b></div>
            {(funnel.stages || []).map((st, i) => (
              <div key={i} style={{ fontSize: 13 }}>{st.label}: <b>{st.survivors}</b> survived</div>
            ))}
            {Object.keys(funnel.rejected_by || {}).length > 0 && (
              <div style={{ marginTop: 8 }}>
                <div style={{ fontSize: 11, color: 'var(--ink-500)' }}>Rejected by filter:</div>
                {Object.entries(funnel.rejected_by).map(([k, n]) => (
                  <div key={k} style={{ fontSize: 12.5, color: 'var(--ink-700)' }}>· {FUNNEL_FILTER_LABELS[k] || k}: {n}</div>
                ))}
              </div>
            )}
            <div style={{ fontSize: 13, marginTop: 8 }}>Final hits: <b>{funnel.final_hits}</b></div>
          </div>
        )}

        {result?.hits?.length > 0 && (
          <table style={{ width: '100%', fontSize: 12.5, borderCollapse: 'collapse' }}>
            <thead><tr style={{ textAlign: 'left', color: 'var(--ink-500)' }}>
              <th>Ticker</th><th>Price</th><th>YTD</th><th>EV/EBITDA</th><th>% of 6mo high</th>
            </tr></thead>
            <tbody>
              {result.hits.map(h => (
                <tr key={h.ticker} style={{ borderTop: '1px solid var(--ink-100)' }}>
                  <td>{h.ticker}</td>
                  <td>{h.current_price != null ? `$${Number(h.current_price).toFixed(2)}` : '—'}</td>
                  <td>{h.ytd_return != null ? `${(h.ytd_return * 100).toFixed(1)}%` : '—'}</td>
                  <td>{h.ev_ebitda != null ? Number(h.ev_ebitda).toFixed(1) : '—'}</td>
                  <td>{h.pct_of_6mo_high != null ? `${(h.pct_of_6mo_high * 100).toFixed(0)}%` : '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
        {funnel && (result?.hits?.length || 0) === 0 && !loading &&
          <div style={{ color: 'var(--ink-500)', fontSize: 13 }}>No matches. The funnel above shows which filter eliminated the candidates.</div>}
      </div>
    </div>
  );
};
