/* MInsightsScreen — merchant home insights detail.
   One screen drives both:
     a) Tapping a KPI tile (Points awarded / Coupons redeemed / New onboards
        / Active now) → filtered ledger view headed by the chosen KPI's
        current value, with the underlying transactions listed below.
     b) Tapping "View all" on the Live ledger section → same screen with
        no KPI focus (the duration chip strip still controls the listed
        rows).

   The duration chips (Today / This Month / This Year) refetch the
   dashboard and ledger via the BE `period` query string. Always uses
   `GET /merchants/{key}/dashboard?period=…` plus
   `GET /merchants/{key}/ledger?period=…`.

   Props:
     - dark    : boolean — applies dark surface tokens
     - merchant: string — merchant key (passed for parity with other screens)
     - focus   : string — 'pointsAwarded' | 'couponsRedeemed' | 'newOnboards'
                          | 'activeNow' | 'ledger'  (drives the header title)
     - onBack  : () => void — pop back to /m/home
*/

function MInsightsScreen({ dark, merchant, focus, onBack }) {
  // Period filter — chip strip below the header. UTC midnight = "today".
  const [period, setPeriod] = React.useState('today');

  // Active merchant key — same resolution rule as MerchantHomeScreen: in
  // API mode prefer the active profile's merchantKey, otherwise fall back
  // to the `merchant` prop passed through from the router.
  const apiKey = window.KP_USE_API && (getActiveProfileLocal() || {}).merchantKey;
  const key = apiKey || merchant;

  // Fetch dashboard (for the KPI values) + ledger feed in parallel.
  // Both refetch when period changes.
  const { data: dash } = useService(
    () => KP.config.useApi ? KP.request('GET', `/merchants/${key}/dashboard?period=${period}`, { auth: true }) : Promise.resolve(null),
    [key, period],
  );
  const { data: rows, loading: loadingRows } = useService(
    () => KP.config.useApi ? KP.request('GET', `/merchants/${key}/ledger?period=${period}`, { auth: true }) : Promise.resolve([]),
    [key, period],
  );

  const muted = dark ? 'var(--fg-on-dark-muted)' : 'var(--fg-tertiary)';
  const surface = dark ? 'rgba(255,255,255,0.04)' : 'var(--surface-3)';
  const border  = dark ? 'rgba(255,255,255,0.08)' : 'var(--border-card)';

  // Title + KPI value for the hero strip. `focus` is the KPI label the
  // user tapped; map it to the BE's label string used in the kpi list.
  const focusLabelMap = {
    pointsAwarded:   'Points awarded',
    couponsRedeemed: 'Coupons redeemed',
    newOnboards:     'New onboards',
    activeNow:       'Active now',
    ledger:          'Live ledger',
  };
  const heroLabel = focusLabelMap[focus] || 'Live ledger';
  const heroKpi = (dash && Array.isArray(dash.kpis))
    ? dash.kpis.find((k) => k.label === heroLabel)
    : null;

  // Filter the ledger rows by KPI focus so a KPI-tile entry only shows
  // the transactions that contributed to its number (awards for points
  // awarded, redemptions for coupons redeemed). 'ledger' / 'activeNow' /
  // 'newOnboards' show all rows because they're either holistic or
  // derived from a different table (membership), not the scan ledger.
  const filteredRows = (rows || []).filter((r) => {
    if (focus === 'pointsAwarded')   return r.tone === 'pos';
    if (focus === 'couponsRedeemed') return r.tone === 'neg';
    return true;
  });

  const chips = [
    { key: 'today', label: 'Today' },
    { key: 'month', label: 'This month' },
    { key: 'year',  label: 'This year' },
  ];

  return (
    <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ padding: '20px 20px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={onBack} style={iconBtnM(dark)} aria-label="Back"><I.Back width="20" height="20"/></button>
        <div style={{ fontSize: 14, fontWeight: 700 }}>{heroLabel}</div>
        <div style={{ width: 38 }}/>
      </div>

      {/* Hero KPI strip — only renders when the focus is a KPI (not the
          live-ledger view-all variant where the KPI value isn't relevant). */}
      {focus && focus !== 'ledger' && (
        <div style={{ padding: '14px 20px 0' }}>
          <div style={{
            background: 'var(--gradient-ambient)', color: 'white', borderRadius: 18, padding: 18,
            position: 'relative', overflow: 'hidden', boxShadow: 'var(--shadow-card-hero)',
          }}>
            <AmbientField/>
            <DotPattern color="rgba(255,255,255,0.16)" size={12}/>
            <div style={{ position: 'relative' }}>
              <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: 1.4, textTransform: 'uppercase', opacity: 0.85 }}>
                {heroLabel}
              </div>
              <div style={{ fontSize: 36, fontWeight: 800, marginTop: 6, lineHeight: 1 }}>
                {heroKpi ? heroKpi.value : '—'}
              </div>
              <div style={{ fontSize: 12, opacity: 0.85, marginTop: 6 }}>
                {heroKpi ? heroKpi.delta : ''}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Period chips */}
      <div style={{ padding: '14px 20px 0', display: 'flex', gap: 6, overflowX: 'auto', scrollbarWidth: 'none' }}>
        {chips.map((c) => {
          const on = period === c.key;
          return (
            <button key={c.key} onClick={() => setPeriod(c.key)} style={{
              flexShrink: 0,
              padding: '8px 14px', borderRadius: 999, fontFamily: 'inherit',
              background: on ? 'var(--accent-500)' : surface,
              color: on ? 'white' : 'inherit',
              border: on ? 'none' : `1px solid ${border}`,
              fontSize: 12, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap',
            }}>{c.label}</button>
          );
        })}
      </div>

      {/* Scrollable list */}
      <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '14px 20px 30px' }}>
        <div style={{ fontSize: 12, color: muted, marginBottom: 10 }}>
          {filteredRows.length} {filteredRows.length === 1 ? 'transaction' : 'transactions'}
          {' · '}{chips.find((c) => c.key === period).label.toLowerCase()}
        </div>

        {loadingRows && !rows ? (
          <LoadingShell dark={dark} label="Loading transactions…"/>
        ) : filteredRows.length === 0 ? (
          <div style={{ padding: '40px 12px', textAlign: 'center', color: muted, fontSize: 13 }}>
            No transactions match this filter.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {filteredRows.map((r, i) => (
              <Reveal key={i} delay={Math.min(i, 10) * 40}>
                <div style={{
                  background: surface, border: `1px solid ${border}`,
                  borderRadius: 14, padding: '10px 14px',
                  display: 'flex', alignItems: 'center', gap: 12,
                }}>
                  <Avatar name={r.n || r.name || 'Member'} size={36} color="var(--warm-700)"/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 700 }}>{r.n || r.name || 'Member'}</div>
                    <div style={{ fontSize: 11, color: muted }}>{(r.t || r.title || '')} · {(r.w || r.time || '')}</div>
                  </div>
                  <div style={{
                    fontSize: 14, fontWeight: 800,
                    color: r.tone === 'pos' ? 'var(--status-success)'
                      : r.tone === 'neg' ? 'var(--status-danger)'
                      : 'var(--accent-500)',
                  }}>{r.v || r.amount}</div>
                </div>
              </Reveal>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { MInsightsScreen });
