File size: 13,280 Bytes
fa9c65f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import { Panel } from './Panel';
import { getCSSColor } from '@/utils';
import type { CountryScore } from '@/services/country-instability';
import { t } from '../services/i18n';
import { h, replaceChildren, rawHtml, setTrustedHtml, trustedHtml, type TrustedHtml } from '@/utils/dom-utils';
import type { CachedRiskScores } from '@/services/cached-risk-scores';
import { toCountryScore } from '@/services/cached-risk-scores';
import { renderFollowButton } from '@/utils/follow-button';
import {
  getFollowed,
  isFollowFeatureEnabled,
  subscribe as subscribeFollowed,
} from '@/services/followed-countries';
import {
  partitionByFollowed,
  shouldRenderSectionLabels,
} from './_cii-panel-partition';

export const CII_METHODOLOGY_HREF = '/docs/methodology/cii-risk-scores';

export class CIIPanel extends Panel {
  private scores: CountryScore[] = [];
  private onShareStory?: (code: string, name: string) => void;
  private onCountryClick?: (code: string) => void;
  // Per-row FollowButton teardowns. Keyed by ISO code so we can tear
  // down each one before the row is re-rendered (refresh / renderFromCached
  // both call replaceChildren on this.content). Without this the
  // FollowButton's watchlist + entitlement subscriptions leak each
  // refresh tick β€” CIIPanel re-renders very frequently.
  private followButtonTeardowns = new Map<string, () => void>();
  // U6 β€” teardown for the watchlist subscription installed in the
  // constructor. Re-renders the current rows whenever the followed list
  // changes (anonymous: localStorage write or cross-tab `storage` event;
  // signed-in: Convex `listFollowed` snapshot). Fired on `destroy()`.
  private followedUnsubscribe: (() => void) | null = null;

  constructor() {
    super({
      id: 'cii',
      title: t('panels.cii'),
      // Two keys (#3725 review): infoTooltip ships translated in all 21 locales;
      // methodologyLink is shipped en-only as a stop-gap so the disclosure link is
      // present in every locale immediately. Translators can localize the link
      // asynchronously without holding back the transparency feature.
      infoTooltip: `${t('components.cii.infoTooltip')} ${t('components.cii.methodologyLink')}`,
      defaultRowSpan: 2,
    });
    this.showLoading(t('common.loading'));

    // U6 β€” re-render rows on every watchlist mutation so the pinned-to-top
    // group stays in sync. We re-render the cached scores in place rather
    // than re-fetch β€” the data hasn't changed, only the partition order.
    // The handler is a no-op until `this.scores` is populated by the first
    // `refresh()` / `renderFromCached()` call.
    this.followedUnsubscribe = subscribeFollowed(() => {
      this.rerenderRows();
    });
  }

  public setShareStoryHandler(handler: (code: string, name: string) => void): void {
    this.onShareStory = handler;
  }

  public setCountryClickHandler(handler: (code: string) => void): void {
    this.onCountryClick = handler;
  }

  private getLevelColor(level: CountryScore['level']): string {
    switch (level) {
      case 'critical': return getCSSColor('--semantic-critical');
      case 'high': return getCSSColor('--semantic-high');
      case 'elevated': return getCSSColor('--semantic-elevated');
      case 'normal': return getCSSColor('--semantic-normal');
      case 'low': return getCSSColor('--semantic-low');
    }
  }

  private getLevelEmoji(level: CountryScore['level']): string {
    switch (level) {
      case 'critical': return 'πŸ”΄';
      case 'high': return '🟠';
      case 'elevated': return '🟑';
      case 'normal': return '🟒';
      case 'low': return 'βšͺ';
    }
  }

  private static readonly SHARE_SVG: TrustedHtml = trustedHtml(
    '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12v7a2 2 0 002 2h12a2 2 0 002-2v-7"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/></svg>',
    'Static share icon SVG defined in source',
  );

  private buildTrendArrow(trend: CountryScore['trend'], change: number): HTMLElement {
    if (trend === 'rising') return h('span', { className: 'trend-up' }, `↑${change > 0 ? change : ''}`);
    if (trend === 'falling') return h('span', { className: 'trend-down' }, `↓${Math.abs(change)}`);
    return h('span', { className: 'trend-stable' }, 'β†’');
  }

  private buildCountry(country: CountryScore): HTMLElement {
    const color = this.getLevelColor(country.level);
    const emoji = this.getLevelEmoji(country.level);

    const shareBtn = h('button', {
      className: 'cii-share-btn',
      dataset: { code: country.code, name: country.name },
      title: t('common.shareStory'),
    });
    shareBtn.appendChild(rawHtml(CIIPanel.SHARE_SVG));

    // First child: per-row FollowButton (size sm). Insertion happens
    // before the existing .cii-header so the star renders at the start
    // of the row. The host wrapper owns the button's innerHTML across
    // re-renders; teardown is tracked in `followButtonTeardowns` and
    // fired before every wholesale rebuild + on panel destroy.
    const followHost = h('span', {
      className: 'cii-follow-btn-host',
      dataset: { code: country.code },
    });
    const handle = renderFollowButton({
      countryCode: country.code,
      countryName: country.name,
      size: 'sm',
    });
    setTrustedHtml(followHost, trustedHtml(handle.html, "legacy direct innerHTML migration"));
    // Attach immediately. The host doesn't need to be DOM-connected for
    // `attach()` to install its delegated click + subscription listeners,
    // and `attach()` re-renders into the host so any state drift is
    // resolved on mount.
    const teardown = handle.attach(followHost);
    this.followButtonTeardowns.set(country.code, teardown);
    // Stop click bubbling so the per-row `onCountryClick` doesn't fire
    // when the user clicks the star (matches the `cii-share-btn`
    // stopPropagation pattern in `bindShareButtons`).
    followHost.addEventListener('click', (e) => e.stopPropagation());

    return h('div', { className: 'cii-country', dataset: { code: country.code } },
      followHost,
      h('div', { className: 'cii-header' },
        h('span', { className: 'cii-emoji' }, emoji),
        h('span', { className: 'cii-name' }, country.name),
        h('span', { className: 'cii-score' }, String(country.score)),
        this.buildTrendArrow(country.trend, country.change24h),
        shareBtn,
      ),
      h('div', { className: 'cii-bar-container' },
        h('div', { className: 'cii-bar', style: `width: ${country.score}%; background: ${color};` }),
      ),
      h('div', { className: 'cii-components' },
        h('span', { title: t('common.unrest') }, `U:${country.components.unrest}`),
        h('span', { title: t('common.conflict') }, `C:${country.components.conflict}`),
        h('span', { title: t('common.security') }, `S:${country.components.security}`),
        h('span', { title: t('common.information') }, `I:${country.components.information}`),
      ),
    );
  }

  private tearDownFollowButtons(): void {
    for (const teardown of this.followButtonTeardowns.values()) {
      try {
        teardown();
      } catch {
        /* swallow β€” teardown should never throw, but be defensive */
      }
    }
    this.followButtonTeardowns.clear();
  }

  /**
   * U6 β€” Build the list element from already-loaded scores. Inserts a
   * single "Following" / "All" section pair when BOTH groups are
   * non-empty; otherwise renders the unpartitioned list (no divider, no
   * label) so the zero-followed and all-followed cases match today's UX.
   *
   * Partition logic lives in `_cii-panel-partition.ts` so it's
   * unit-testable without the Panel/DOM/i18n transitive deps.
   *
   * Caller must call `tearDownFollowButtons()` BEFORE invoking this
   * (every row mounts a fresh FollowButton; the previous batch's
   * subscriptions must be released first).
   */
  private buildList(scores: CountryScore[]): HTMLElement {
    // Gate the partition input on the feature flag β€” `getFollowed()` reads
    // localStorage even when the flag is off (anonymous mode reads aren't
    // short-circuited, only mutations are). When the flag is OFF, treat
    // the followed list as `[]` so partitionByFollowed becomes a no-op:
    // rows render in the original score order, no FOLLOWING / ALL labels.
    // Without this gate, flag-off users would see partitioning + section
    // labels even though the FollowButton / chip surface is hidden.
    const followedCodes = isFollowFeatureEnabled() ? getFollowed() : [];
    const partition = partitionByFollowed(scores, followedCodes);

    if (!shouldRenderSectionLabels(partition)) {
      // Zero-followed OR all-followed β†’ render the original order with
      // no divider. Behaviour identical to pre-U6.
      return h(
        'div',
        { className: 'cii-list' },
        ...scores.map((s) => this.buildCountry(s)),
      );
    }

    const { followed, unfollowed } = partition;
    const followingLabel = h(
      'div',
      { className: 'cii-section-label' },
      t('components.cii.sectionFollowing'),
    );
    const allLabel = h(
      'div',
      { className: 'cii-section-label' },
      t('components.cii.sectionAll'),
    );

    return h(
      'div',
      { className: 'cii-list' },
      followingLabel,
      ...followed.map((s) => this.buildCountry(s)),
      allLabel,
      ...unfollowed.map((s) => this.buildCountry(s)),
    );
  }

  private buildMethodologyFooter(): HTMLElement {
    return h('div', { className: 'cii-methodology-footer' },
      h('a', {
        href: CII_METHODOLOGY_HREF,
        target: '_blank',
        rel: 'noopener noreferrer',
      }, t('components.cii.methodologyLink')),
    );
  }

  private formatCachedSourceDetail(cached: Pick<CachedRiskScores, 'degraded' | 'stale'>): string {
    const flags: string[] = [];
    if (cached.degraded) flags.push(t('components.cii.sourceStates.degraded'));
    if (cached.stale) flags.push(t('components.cii.sourceStates.stale'));
    return flags.join(' Β· ');
  }

  private updateSourceBadge(cached: Pick<CachedRiskScores, 'degraded' | 'stale'> | null): void {
    if (!cached) {
      this.clearDataBadge();
      return;
    }
    const detail = this.formatCachedSourceDetail(cached);
    this.setDataBadge('cached', detail || undefined);
  }

  /**
   * U6 β€” Cheap re-render path used by the watchlist subscription. Rebuilds
   * the row list from the cached `this.scores` (no re-fetch) so the
   * partition order updates in one tick. No-op if no scores have been
   * loaded yet (the next refresh / renderFromCached will pick up the
   * watchlist on its own).
   */
  private rerenderRows(): void {
    if (this.scores.length === 0) return;
    const withData = this.scores.filter((s) => s.score > 0);
    if (withData.length === 0) return;
    this.tearDownFollowButtons();
    replaceChildren(this.content, this.buildList(withData), this.buildMethodologyFooter());
    this.bindShareButtons();
  }

  private bindShareButtons(): void {
    if (!this.onShareStory && !this.onCountryClick) return;

    this.content.querySelectorAll('.cii-country').forEach(el => {
      el.addEventListener('click', (e) => {
        const target = e.currentTarget as HTMLElement;
        const code = target.dataset.code;
        if (code && this.onCountryClick) {
          this.onCountryClick(code);
        }
      });
    });

    this.content.querySelectorAll('.cii-share-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        const el = e.currentTarget as HTMLElement;
        const code = el.dataset.code || '';
        const name = el.dataset.name || '';
        if (code && name && this.onShareStory) this.onShareStory(code, name);
      });
    });
  }

  public renderUnavailable(): void {
    this.scores = [];
    this.setCount(0);
    this.setErrorState(false);
    this.setDataBadge('unavailable');
    this.tearDownFollowButtons();
    replaceChildren(
      this.content,
      h('div', { className: 'empty-state' }, t('common.failedCII')),
      this.buildMethodologyFooter(),
    );
  }

  public renderFromCached(cached: CachedRiskScores): void {
    const scores = cached.cii.map(toCountryScore).filter(s => s.score > 0);
    if (scores.length === 0) return;
    this.scores = scores;
    this.updateSourceBadge(cached);
    this.setCount(scores.length);
    this.setErrorState(false);
    // Tear down previous FollowButtons before mounting the new batch.
    this.tearDownFollowButtons();
    replaceChildren(this.content, this.buildList(scores), this.buildMethodologyFooter());
    this.bindShareButtons();
    console.log(`[CIIPanel] Rendered ${scores.length} countries from cached/bootstrap data`);
  }

  public getScores(): CountryScore[] {
    return this.scores;
  }

  public override destroy(): void {
    this.tearDownFollowButtons();
    if (this.followedUnsubscribe) {
      try {
        this.followedUnsubscribe();
      } catch {
        /* swallow β€” unsubscribe should never throw, but be defensive */
      }
      this.followedUnsubscribe = null;
    }
    super.destroy();
  }
}