-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocation.jsx
More file actions
1133 lines (1054 loc) · 48.5 KB
/
Copy pathlocation.jsx
File metadata and controls
1133 lines (1054 loc) · 48.5 KB
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================
// Карточка локации — детальный экран
// ============================================================
// useLocationDeep + audienceMatch — теперь в primitives.jsx (доступны на всех экранах)
// ---------- Severity → tone helper ----------
function severityTone(sev) {
if (sev === 'critical') return 'bad';
if (sev === 'high') return 'bad';
if (sev === 'medium') return 'warn';
return 'mute';
}
// ---------- Add-to-plan integration ----------
// Severity / effectiveDate → due-string в формате Roadmap ('T-N мес' / 'действует' / 'T+N мес')
function deriveDue(effectiveDate, severity, today = new Date()) {
if (effectiveDate) {
const eff = new Date(effectiveDate);
if (!isNaN(eff.getTime())) {
const diffMs = eff.getTime() - today.getTime();
const diffMonths = Math.round(diffMs / (1000 * 60 * 60 * 24 * 30.4));
if (diffMonths <= 0) return 'действует';
if (diffMonths === 1) return 'T-1 мес';
return `T-${diffMonths} мес`;
}
}
if (severity === 'critical') return 'T-1 мес';
if (severity === 'high') return 'T-2 мес';
if (severity === 'medium') return 'T-3 мес';
return 'T-6 мес';
}
// Hook: добавление задачи в Roadmap с дедупликацией по title+source
function useAddToPlan() {
const [tasks, setTasks] = useLocalState('tasks', window.TASKS_INIT || []);
const exists = useCallback((draft) =>
tasks.some(t => t.title === draft.title && (t._source || '') === (draft.source || '')),
[tasks]
);
const add = useCallback((draft) => {
if (exists(draft)) return { added: false, reason: 'duplicate' };
const newTask = {
id: 't' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5),
lane: draft.lane || 'docs',
title: draft.title,
due: draft.due || 'T-?',
done: false,
deps: draft.deps || '',
_source: draft.source || null
};
setTasks([...tasks, newTask]);
return { added: true, taskId: newTask.id };
}, [tasks, setTasks, exists]);
return { add, exists, tasks };
}
// Button: «+ в план» / «✓ в плане» (реактивно)
function AddToPlanBtn({ draft, full }) {
const { add, exists } = useAddToPlan();
const inPlan = exists(draft);
return (
<button
onClick={() => { if (!inPlan) add(draft); }}
disabled={inPlan}
className={`btn ghost ${full ? 'full' : 'sm'}`}
style={{
fontSize: 11,
opacity: inPlan ? 0.7 : 1,
cursor: inPlan ? 'default' : 'pointer'
}}
title={inPlan ? 'Уже добавлено' : 'Создать задачу в Roadmap'}
>
{inPlan ? '✓ в плане' : '+ в план'}
</button>
);
}
// ---------- Verification badge ----------
// Phase 6 #28: добавлена поддержка опционального props.deprecatedSince
// для показа конкретной даты («устарело с YYYY-MM») и tooltip.
function VerifyBadge({ status, deprecatedSince, note }) {
if (!status || status === 'verified') return null;
if (status === 'source-only') {
return (
<span
className="tag"
style={{ background: 'var(--warn-soft, rgba(255,180,0,0.12))', color: 'var(--warn)', fontSize: 10 }}
title={note || 'Источник цитирует, но не подтверждён вторым источником'}
>
требует проверки
</span>
);
}
if (status === 'deprecated') {
const label = deprecatedSince ? `устарело с ${deprecatedSince}` : 'устарело';
return (
<span
className="tag"
style={{ background: 'var(--bad-soft, rgba(255,80,80,0.10))', color: 'var(--bad)', fontSize: 10, opacity: 0.85 }}
title={note || (deprecatedSince
? `Данные потеряли актуальность с ${deprecatedSince}. Проверьте обновлённую версию.`
: 'Данные потеряли актуальность.')}
>
⚠ {label}
</span>
);
}
return null;
}
// ---------- TrustMeta — индикатор актуальности данных досье ----------
// Считает блоки с verificationStatus === 'source-only' (требуют проверки)
// и показывает компактную мета-строку.
function countSourceOnly(deep) {
let count = 0;
// Top-level и блоки
for (const key of ['rent', 'realEstate', 'medicine.insurance']) {
const path = key.split('.');
let v = deep;
for (const p of path) v = v && v[p];
if (v && v.verificationStatus === 'source-only') count++;
}
// legal.workPermit2026
if (deep.legal && deep.legal.workPermit2026 && deep.legal.workPermit2026.verificationStatus === 'source-only') count++;
// risks[]
if (Array.isArray(deep.risks)) {
count += deep.risks.filter(r => r.verificationStatus === 'source-only').length;
}
return count;
}
function TrustMeta({ deep }) {
const sourceOnly = useMemo(() => countSourceOnly(deep), [deep]);
const updated = deep.updated || null;
if (!updated && sourceOnly === 0) return null;
return (
<div className="row g-8 mt-10" style={{ flexWrap: 'wrap', alignItems: 'center' }}>
{updated && (
<span className="mono fs-10 t-mute" title="Дата последней верификации данных">
обновлено {updated}
</span>
)}
{sourceOnly > 0 && (
<span className="tag" style={{
fontSize: 10,
background: 'var(--warn-soft, rgba(255,180,0,0.12))',
color: 'var(--warn)'
}} title="Сколько блоков требуют независимой верификации">
{sourceOnly} {sourceOnly === 1 ? 'блок требует проверки' : 'блоков требуют проверки'}
</span>
)}
</div>
);
}
function ScreenLocation({ id }) {
const nav = useNav();
const { profile, update } = useProfile();
const allLocs = window.LOCATIONS || [];
const l = allLocs.find(x => x.id === id);
const { deep, loading: deepLoading } = useLocationDeep(id);
const userTags = (profile && profile.audienceTags) || [];
const isTarget = profile?.targetCity === id;
const [tab, setTab] = useState('health');
const [shortlist, setShortlist] = useLocalState('atlas:shortlist', []);
if (!l) {
return (
<>
<TopBar back="назад" title="Локация" />
<main className="page"><Empty title="Локация не найдена" /></main>
</>
);
}
// computed score — учитывает веса пользователя (profile.weights) если есть
const crit = window.CRITERIA || [];
const userWeights = profile?.weights || null;
const weightOf = (c) => userWeights && userWeights[c.id] != null ? userWeights[c.id] : c.weight;
const totW = crit.reduce((s, c) => s + (weightOf(c) || 0), 0) || 1;
const breakdown = crit.map(c => ({ id: c.id, label: c.label, weight: weightOf(c), value: c.get(l) || 0 }));
const score = breakdown.reduce((acc, b) => acc + b.value * b.weight, 0) / totW / 10;
const tone = score >= 7 ? 'good' : score >= 5 ? 'warn' : 'bad';
const burn = l.rent + l.food + l.util + l.med + l.transport + l.tech + l.reserve;
const savings = 2400 - burn;
const shortlisted = shortlist.includes(l.id);
return (
<>
<TopBar
back={l.country.split(',')[0]}
title={l.name}
actions={
<>
<IconBtn name="target"
onClick={() => update && update({ targetCity: isTarget ? null : id })}
on={isTarget}
label={isTarget ? 'Снять цель' : 'Сделать целевым городом'} />
<IconBtn name={shortlisted ? 'check' : 'plus'}
onClick={() => setShortlist(shortlisted ? shortlist.filter(x => x !== l.id) : [...shortlist, l.id])}
on={shortlisted}
label={shortlisted ? 'Убрать из шорт-листа' : 'В шорт-лист'} />
</>
}
/>
<main className="page">
{/* Hero — score + summary */}
<Card padding={18} elev>
<div className="row between center">
<span className="eyebrow">{l.country} · {l.flag}</span>
<div className="row g-6 center">
{isTarget && <Tag accent>✓ ваш целевой</Tag>}
{l.eu && <Tag tone="good">ЕС · мед</Tag>}
</div>
</div>
{deep && <TrustMeta deep={deep} />}
<div className="row between baseline mt-12">
<div>
<h1 className="h1" style={{ fontSize: 38, lineHeight: 1 }}>{l.name}</h1>
<div className="mono fs-11 t-mute mt-6">{l.sea ? `${l.sea} море` : 'континент'} · {l.pine}</div>
</div>
<div className="col end g-2">
<span className={`stat-num fs-44 t-${tone}`}>{score.toFixed(1)}</span>
<span className="mono fs-10 t-mute">/ 10 · по семье</span>
</div>
</div>
{l.notes && (
<div className="serif-italic fs-13 t-soft mt-14" style={{ lineHeight: 1.5 }}>
«{l.notes}»
</div>
)}
</Card>
{/* Tabs — базовые 6 + расширенные 5 (только если есть deep-досье) */}
<div className="mt-16">
<div className="pillrow" style={{ overflowX: 'auto', flexWrap: 'nowrap', margin: '0 -16px', padding: '0 16px' }}>
{[
['health', 'здоровье'],
['budget', 'бюджет'],
['visa', 'визы'],
['gastro', 'ЖКТ'],
['climate', 'климат'],
['weights', 'веса'],
// Расширенные — только при наличии deep-данных
...(deep ? [
['rent', 'жильё'],
['legal', 'легализация'],
['infra', 'быт'],
['community', 'сообщество'],
['risks', 'риски']
] : [])
].map(([id, l2]) => (
<button key={id} className={`pill ${tab === id ? 'on' : ''} shrink-0`} onClick={() => setTab(id)}>{l2}</button>
))}
</div>
{deepLoading && (
<div className="mt-10">
<Skeleton lines={3} gap={8} height={14} />
<div className="mono fs-10 t-mute mt-8">Загружаем расширенное досье…</div>
</div>
)}
</div>
<div className="mt-14">
{tab === 'health' && <TabHealth l={l} />}
{tab === 'budget' && <TabBudget l={l} burn={burn} savings={savings} />}
{tab === 'visa' && <TabVisa l={l} />}
{tab === 'gastro' && <TabGastro l={l} />}
{tab === 'weights' && <TabWeights breakdown={breakdown} l={l} score={score} />}
{tab === 'climate' && <TabClimate l={l} />}
{tab === 'rent' && deep && <TabRent deep={deep} userTags={userTags} />}
{tab === 'legal' && deep && <TabLegal deep={deep} userTags={userTags} />}
{tab === 'infra' && deep && <TabInfra deep={deep} userTags={userTags} />}
{tab === 'community' && deep && <TabCommunity deep={deep} userTags={userTags} />}
{tab === 'risks' && deep && <TabRisks deep={deep} userTags={userTags} />}
</div>
{/* Similar */}
<div className="section-head">
<h2 className="title">Похожие локации</h2>
</div>
<div className="row g-8" style={{ overflowX: 'auto', margin: '0 -16px', padding: '0 16px 8px' }}>
{allLocs
.filter(x => x.id !== l.id && x.sea === l.sea)
.slice(0, 5)
.map(x => (
<div key={x.id} className="card shrink-0" style={{ width: 160, padding: 12 }} onClick={() => nav.goto('location', { id: x.id })}>
<div className="serif fs-15">{x.name}</div>
<div className="mono fs-10 t-mute mt-2">{x.country.split(',')[0]}</div>
<div className="row g-6 mt-8">
<span className="tag">{x.humidity}%</span>
<span className="tag">aqi {x.aqi}</span>
</div>
</div>
))
}
</div>
{/* CTA */}
<div className="row g-8 mt-20">
<button className="btn full" onClick={() => nav.goto('compare', { ids: [l.id, ...shortlist.filter(x => x !== l.id)] })}>сравнить</button>
<button className="btn primary full" onClick={() => nav.switchTab('chat')}>спросить AI</button>
</div>
</main>
</>
);
}
// ============== Tabs ==============
function TabHealth({ l }) {
const nav = useNav();
const { profile } = useProfile();
const allConds = window.CONDITIONS || [];
const userCondIds = (profile?.health?.conditions || []).map(c => c.id);
// Если у пользователя есть выбранные диагнозы — показываем только их,
// иначе — общую информацию по всем (с пометкой).
const conds = userCondIds.length > 0
? allConds.filter(c => userCondIds.includes(c.id))
: allConds;
const showingAll = userCondIds.length === 0 && allConds.length > 0;
const factors = [
{ label: 'Влажность лето', v: `${l.humidity}%`, ok: l.humidity >= 55 && l.humidity <= 70, meta: 'оптимум 55–65%' },
{ label: 'Среднегодовая T', v: `${l.temp}°C`, ok: l.temp >= 10 && l.temp <= 18, meta: 'оптимум 12–16°C' },
{ label: 'AQI · PM2.5', v: l.aqi, ok: l.aqi <= 35, meta: 'WHO < 35' },
{ label: 'Жёсткость воды', v: `${l.waterHard} мг·экв`, ok: l.waterHard <= 5, meta: 'мягкая ≤ 5' },
{ label: 'Хвойные', v: l.pine.split(' ')[0], ok: !!l.pine, meta: 'фитонциды' },
{ label: 'Доступ к ЕС-медицине', v: l.eu ? 'да' : 'нет', ok: l.eu, meta: 'дупилумаб по НЗОК' }
];
return (
<div className="col g-16">
<Card padding={0}>
{factors.map((f, i) => (
<div key={i} className="row between center" style={{
padding: '12px 14px',
borderBottom: i < factors.length - 1 ? '1px solid var(--line-soft)' : 'none'
}}>
<div className="col" style={{ minWidth: 0 }}>
<span className="fs-13 t-soft">{f.label}</span>
<span className="mono fs-10 t-mute mt-2">{f.meta}</span>
</div>
<div className="row g-8 center">
<span className={`mono fs-13 t-${f.ok ? 'good' : 'warn'}`}>{f.v}</span>
<span className={`dot ${f.ok ? 'good' : 'warn'}`}></span>
</div>
</div>
))}
</Card>
{conds.length > 0 && window.scoreLocationForCondition && (
<Card
title={showingAll ? 'По диагнозам (общая информация)' : 'По вашим диагнозам'}
sub={showingAll
? 'Добавьте диагнозы в профиле, чтобы видеть только релевантные.'
: 'Совместимость 0–100 для каждого диагноза из вашего профиля.'}
padding={14}
>
<div className="col g-10 mt-4">
{conds.map(c => {
const s = window.scoreLocationForCondition(l, c);
const stone = s >= 70 ? 'good' : s >= 50 ? 'warn' : 'bad';
return (
<div key={c.id} className="col g-6">
<div className="row between baseline">
<span className="fs-12">{c.name} <span className="mono fs-10 t-mute">· {c.icd}</span></span>
<span className={`mono fs-12 t-${stone}`}>{Math.round(s)}</span>
</div>
<div className={`bar ${stone}`}><span style={{ width: `${s}%` }}/></div>
</div>
);
})}
</div>
<button
className="btn full ghost"
style={{ marginTop: 14, fontSize: 12 }}
onClick={() => nav.goto('conditions')}
>
атлас здоровья · все диагнозы →
</button>
</Card>
)}
</div>
);
}
function TabBudget({ l, burn, savings }) {
const items = [
['Аренда дома', l.rent],
['Продукты', l.food],
['Коммуналка', l.util],
['Медицина', l.med],
['Транспорт', l.transport],
['Health-tech', l.tech],
['Резерв', l.reserve]
];
const max = Math.max(...items.map(i => i[1]));
return (
<div className="col g-16">
<Card padding={14}>
<div className="row between center">
<span className="eyebrow">бюджет / мес · $</span>
<span className="mono fs-11 t-mute">2 человека</span>
</div>
<div className="row baseline g-8 mt-12">
<span className="stat-num fs-30">{fmtMoney(burn)}</span>
<span className="mono fs-11 t-mute">расход</span>
</div>
<div className="row between mt-8 fs-11 mono">
<span className="t-mute">сбережения</span>
<span className={savings > 0 ? 't-good' : 't-bad'}>{savings > 0 ? '+' : ''}{fmtMoney(savings)} ({((savings/2400)*100).toFixed(0)}%)</span>
</div>
</Card>
<Card padding={14}>
<div className="eyebrow mb-8">структура</div>
<div className="col g-8 mt-8">
{items.map(([label, v]) => (
<div key={label} className="col g-4">
<div className="row between baseline fs-12">
<span className="t-soft">{label}</span>
<span className="mono">{fmtMoney(v)}</span>
</div>
<div className="bar"><span style={{ width: `${(v/max)*100}%` }}/></div>
</div>
))}
</div>
</Card>
{l.basketUSD && (
<Card title="Продуктовая корзина" sub="10 позиций · Numbeo актуальная корзина" padding={14}
action={<button className="action mono fs-11" onClick={() => nav.goto('basket')}>детали →</button>}>
<div className="row between center mt-4">
<span className="fs-13 t-soft">итого</span>
<span className="mono fs-15 fw-500">{fmtMoney(Object.values(l.basketUSD).reduce((s, x) => s + x, 0))}</span>
</div>
</Card>
)}
</div>
);
}
function TabVisa({ l }) {
return (
<div className="col g-16">
<Card padding={14}>
<div className="eyebrow mb-8">для граждан РФ</div>
<div className="serif fs-22 mt-4">{l.visaRu?.type === 'visa-free' ? 'Безвиз' :
l.visaRu?.type === 'evisa' ? 'Электронная виза' :
l.visaRu?.type === 'visa-required' ? 'Виза требуется' :
l.visaRu?.type === 'domestic' ? 'Без релокации' : l.visa}</div>
{l.visaRu?.days && <div className="mono fs-12 t-mute mt-4">{l.visaRu.days} дней · {l.visaRu.asOf}</div>}
{l.visaRu?.notes && <div className="fs-13 t-soft mt-12" style={{lineHeight: 1.55}}>{l.visaRu.notes}</div>}
</Card>
<Card padding={14}>
<div className="eyebrow mb-8">налогообложение</div>
<div className="row between baseline">
<span className="serif fs-18">{l.tax}</span>
<span className="mono fs-14 t-accent">{l.taxRate}%</span>
</div>
</Card>
<Card padding={14}>
<div className="row between center">
<span className="eyebrow">юрисдикц. риск</span>
<span className="mono fs-12">{l.jurisdictionRisk} / 5</span>
</div>
<Bar value={l.jurisdictionRisk * 20}
tone={l.jurisdictionRisk >= 4 ? 'bad' : l.jurisdictionRisk >= 3 ? 'warn' : 'good'} />
<div className="fs-11 t-mute mt-8 mono">риск изменения правил 5 лет</div>
</Card>
</div>
);
}
function TabGastro({ l }) {
return (
<Card padding={14}>
<div className="row between center">
<span className="eyebrow t-gastro">гастро-индекс</span>
<span className="mono fs-15 t-gastro">{l.gastroScore || '—'} / 5</span>
</div>
<Bar value={(l.gastroScore || 0) * 20} tone="gastro" />
{l.gastroClinic && (
<div className="fs-13 t-soft mt-14" style={{ lineHeight: 1.55 }}>
<span className="eyebrow">клиники</span>
<div className="mt-6">{l.gastroClinic}</div>
</div>
)}
</Card>
);
}
function TabWeights({ breakdown, l, score }) {
const nav = useNav();
return (
<Card title="Score breakdown" sub="по вашим весам критериев" padding={14}
action={<button className="action mono fs-11" onClick={() => nav.goto('compare')}>веса →</button>}>
<div className="col g-10 mt-8">
{breakdown.map(b => {
const tone = b.value >= 70 ? 'good' : b.value >= 50 ? 'warn' : 'bad';
return (
<div key={b.id} className="col g-4">
<div className="row between baseline">
<span className="fs-12 t-soft">{b.label}</span>
<span className="row g-8 mono fs-11">
<span className="t-mute">×{b.weight}</span>
<span className={`t-${tone}`} style={{ width: 32, textAlign: 'right' }}>{Math.round(b.value)}</span>
</span>
</div>
<div className={`bar ${tone}`}><span style={{ width: `${b.value}%` }}/></div>
</div>
);
})}
</div>
<div className="divider"></div>
<div className="row between baseline">
<span className="fs-12 t-soft">итоговый score</span>
<span className="stat-num fs-22 t-accent">{score.toFixed(2)}</span>
</div>
</Card>
);
}
function TabClimate({ l }) {
const months = ['Я','Ф','М','А','М','И','И','А','С','О','Н','Д'];
return (
<div className="col g-14">
<Card padding={14}>
<div className="eyebrow mb-8">пыльцевой календарь · 1–5</div>
<div className="row g-4 mt-4" style={{justifyContent: 'space-between'}}>
{(l.pollen || []).map((v, i) => (
<div key={i} className="col center g-4">
<div style={{
width: 18, height: 32, borderRadius: 3,
background: `color-mix(in oklab, var(--warn) ${v * 18}%, var(--bg-soft))`,
display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
fontFamily: 'JetBrains Mono', fontSize: 9, color: v >= 4 ? 'var(--bg)' : 'var(--ink-mute)', padding: 2
}}>{v}</div>
<span className="mono fs-9 t-mute">{months[i]}</span>
</div>
))}
</div>
<div className="fs-11 t-mute mt-10 mono">пик пыления хвойных · апрель–май</div>
</Card>
<Card padding={14}>
<div className="eyebrow mb-8">микро-климат</div>
<div className="col g-8 mt-4">
<StatRow label="Хвойные" value={l.pine} />
<StatRow label="Жёсткость воды" value={`${l.waterHard} мг·экв`} tone={l.waterHard <= 5 ? 'good' : 'warn'} />
<StatRow label="Радон" value={l.radon} />
<StatRow label="Сейсмика" value={`${l.earthquake} баллов`} tone={l.earthquake >= 6 ? 'warn' : ''} />
<StatRow label="Интернет" value={`${l.internet} Mbps`} />
<StatRow label="«Эффект ЮБК»" value={`${l.ybkScore} / 5`} tone={l.ybkScore >= 4 ? 'good' : ''} />
</div>
</Card>
</div>
);
}
// ============================================================
// Расширенные табы — питаются из LocationLoader (deep dossier)
// Аудитория-aware: фильтруют по profile.audienceTags
// ============================================================
// ---------- TAB: ЖИЛЬЁ ----------
function TabRent({ deep, userTags }) {
const nav = useNav();
const r = deep.rent;
const re = deep.realEstate;
if (!r && !re) return <Empty title="Нет данных по жилью" />;
return (
<div className="col g-14">
{r && (
<Card padding={14}>
<div className="row between center">
<span className="eyebrow">аренда · долгосрок</span>
<VerifyBadge status={r.verificationStatus} deprecatedSince={r.deprecatedSince} note={r.deprecationNote} />
</div>
<div className="col g-8 mt-10">
{r.summary && Object.entries(r.summary).map(([k, v]) => (
<StatRow key={k} label={k === '1br' ? '1-комнатная' : k === '2br' ? '2-комнатная' : '3-комнатная'}
value={`$${v[0]}–${v[1]}`} suffix="/мес" />
))}
</div>
{(r.deposit || r.commission) && (
<div className="divider"></div>
)}
{r.deposit && <StatRow label="Депозит" value={r.deposit} />}
{r.commission && <StatRow label="Комиссия" value={r.commission} />}
{r.utilities && (
<>
<div className="eyebrow mt-14 mb-8">коммуналка · сезон</div>
<div className="row g-8">
{r.utilities.summer && (
<div className="card flat" style={{ flex: 1, padding: 10 }}>
<div className="mono fs-10 t-mute">лето</div>
<div className="mono fs-15 t-good">${r.utilities.summer[0]}–{r.utilities.summer[1]}</div>
</div>
)}
{r.utilities.winter && (
<div className="card flat" style={{ flex: 1, padding: 10 }}>
<div className="mono fs-10 t-mute">зима</div>
<div className="mono fs-15 t-warn">${r.utilities.winter[0]}–{r.utilities.winter[1]}</div>
</div>
)}
</div>
</>
)}
{r.seasonality && r.seasonality.warning && (
<div className="serif-italic fs-13 t-soft mt-14" style={{ lineHeight: 1.5, borderLeft: '2px solid var(--warn)', paddingLeft: 10 }}>
⚠️ {r.seasonality.warning}
</div>
)}
{r.seasonality && r.seasonality.tip && (
<div className="fs-12 t-soft mt-8">💡 {r.seasonality.tip}</div>
)}
<div className="mt-14">
<AddToPlanBtn draft={{
title: `Найти долгосрочное жильё в ${deep.id}`,
lane: 'prop',
due: 'T-2 мес',
source: `${deep.id}:rent:find`
}} full />
</div>
</Card>
)}
{re && (
<Card padding={14}>
<div className="row between center">
<span className="eyebrow">покупка · ВНЖ</span>
<VerifyBadge status={re.verificationStatus} deprecatedSince={re.deprecatedSince} note={re.deprecationNote} />
</div>
<div className="col g-8 mt-10">
{re.pricePerM2 && re.pricePerM2.center && (
<StatRow label="Центр / м²" value={`$${re.pricePerM2.center[0]}–${re.pricePerM2.center[1]}`} />
)}
{re.pricePerM2 && re.pricePerM2.periphery && (
<StatRow label="Периферия / м²" value={`$${re.pricePerM2.periphery[0]}–${re.pricePerM2.periphery[1]}`} />
)}
{re.minEntry && (
<StatRow label="Минимальный вход" value={`$${re.minEntry.toLocaleString('en-US')}`} />
)}
{re.visaThreshold && (
<StatRow label="Порог ВНЖ (недвиж.)" value={`$${re.visaThreshold.toLocaleString('en-US')}`}
suffix={re.visaThresholdNote || ''} tone="warn" />
)}
</div>
{re.mortgage && (
<>
<div className="eyebrow mt-14 mb-8">ипотека для нерезидента</div>
<div className="col g-6">
{re.mortgage.downPayment && <StatRow label="Первый взнос" value={re.mortgage.downPayment} />}
{re.mortgage.termYears && <StatRow label="Срок" value={`${re.mortgage.termYears[0]}–${re.mortgage.termYears[1]} лет`} />}
{re.mortgage.rate && re.mortgage.rate.USD && <StatRow label="Ставка USD" value={re.mortgage.rate.USD} />}
{re.mortgage.rate && re.mortgage.rate.GEL && <StatRow label="Ставка GEL" value={re.mortgage.rate.GEL} />}
</div>
</>
)}
{re.restrictions && re.restrictions.length > 0 && (
<>
<div className="eyebrow mt-14 mb-6">ограничения</div>
<ul className="col g-4" style={{ margin: 0, paddingLeft: 16 }}>
{re.restrictions.map((x, i) => (
<li key={i} className="fs-12 t-soft" style={{ lineHeight: 1.5 }}>{x}</li>
))}
</ul>
</>
)}
</Card>
)}
<QnaLink
refs={(r && r.qnaRefs || []).concat(re && re.qnaRefs || [])}
label="Ответы по жилью"
loc={deep.id}
seed="аренда квартира депозит коммуналка ипотека"
/>
</div>
);
}
// ---------- TAB: ЛЕГАЛИЗАЦИЯ ----------
function TabLegal({ deep, userTags }) {
const lg = deep.legal;
if (!lg) return <Empty title="Нет данных" />;
const permits = (lg.residencePermits || []).filter(p => audienceMatch(p, userTags));
const taxes = (lg.taxRegimes || []).filter(t => audienceMatch(t, userTags));
const showWorkPermit = lg.workPermit2026 && audienceMatch({ audiences: lg.workPermit2026.affects }, userTags);
return (
<div className="col g-14">
{/* Critical alert: новый закон о труде */}
{showWorkPermit && (
<Card padding={14} style={{ borderLeft: '3px solid var(--bad)' }}>
<div className="row between center">
<span className="eyebrow t-bad">⚠️ критический риск</span>
<VerifyBadge status={lg.workPermit2026.verificationStatus} deprecatedSince={lg.workPermit2026.deprecatedSince} note={lg.workPermit2026.deprecationNote} />
</div>
<div className="serif fs-16 mt-8">Закон о трудовой миграции</div>
<div className="mono fs-11 t-mute mt-2">действует с {lg.workPermit2026.effectiveDate}</div>
<div className="fs-13 t-soft mt-10" style={{ lineHeight: 1.55 }}>{lg.workPermit2026.summary}</div>
<div className="mt-12">
<AddToPlanBtn draft={{
title: `Юрконсультация: новый закон о труде в ${deep.id}`,
lane: 'docs',
due: deriveDue(lg.workPermit2026.effectiveDate, 'critical'),
source: `${deep.id}:legal:work-permit-2026`
}} full />
</div>
</Card>
)}
{/* Визовый режим */}
{lg.visaFree && (
<Card padding={14}>
<div className="eyebrow mb-8">безвиз</div>
<div className="row between baseline">
<span className="serif fs-22">{lg.visaFree.days} дней</span>
<span className="mono fs-11 t-mute">для {(lg.visaFree.forCountries || []).join(', ')}</span>
</div>
</Card>
)}
{/* Типы ВНЖ — фильтр по audienceTags */}
{permits.length > 0 && (
<Card padding={14}>
<div className="row between center">
<span className="eyebrow">типы ВНЖ</span>
{userTags.length > 0 && (
<span className="mono fs-10 t-mute">по вашему профилю</span>
)}
</div>
<div className="col g-10 mt-10">
{permits.map(p => (
<div key={p.id} className="card flat" style={{ padding: 10 }}>
<div className="row between baseline">
<span className="serif fs-14">{p.label}</span>
{p.periodYears && <span className="mono fs-11 t-accent">{p.periodYears} {p.periodYears === 1 ? 'год' : 'лет'}</span>}
</div>
<div className="row g-12 mt-4 fs-11 t-mute mono">
{p.incomeReqUSD && <span>доход ${p.incomeReqUSD}/{p.id === 'real-estate' ? 'покупка' : 'мес'}</span>}
{p.turnoverReq && <span>оборот {p.turnoverReq.toLocaleString()} {p.currency}/год</span>}
</div>
<div className="row mt-8">
<AddToPlanBtn draft={{
title: `Оформить ВНЖ: ${p.label} (${deep.id})`,
lane: 'docs',
due: 'T-3 мес',
source: `${deep.id}:permit:${p.id}`
}} />
</div>
</div>
))}
</div>
</Card>
)}
{/* Налоговые режимы */}
{taxes.length > 0 && (
<Card padding={14}>
<div className="eyebrow mb-8">налоговые режимы</div>
<div className="col g-10 mt-4">
{taxes.map(t => (
<div key={t.id} className="row between baseline">
<div className="col" style={{ minWidth: 0, flex: 1 }}>
<span className="fs-13">{t.label}</span>
{t.limit && <span className="mono fs-10 t-mute mt-2">до {t.limit.toLocaleString()} {t.currency}/год</span>}
</div>
<span className="mono fs-15 t-accent">{t.rate}%</span>
</div>
))}
</div>
</Card>
)}
{/* Экстрадиция */}
{lg.extradition && audienceMatch(lg.extradition, userTags) && (
<Card padding={14} style={{ borderLeft: '3px solid var(--warn)' }}>
<div className="eyebrow t-warn mb-6">экстрадиция</div>
<div className="fs-13 t-soft" style={{ lineHeight: 1.55 }}>
Действующий договор: <strong>{lg.extradition.treaty}</strong>. {lg.extradition.precedents && 'Прецеденты экстрадиции граждан РФ существуют.'}
</div>
<div className="mt-10">
<AddToPlanBtn draft={{
title: `Проконсультироваться с международным юристом по экстрадиции (${deep.id})`,
lane: 'docs',
due: 'T-6 мес',
source: `${deep.id}:legal:extradition`
}} full />
</div>
</Card>
)}
<QnaLink
refs={lg.qnaRefs}
label="Ответы по легализации"
loc={deep.id}
seed="внж виза налог резидентство ип"
/>
</div>
);
}
// ---------- TAB: БЫТ ----------
function TabInfra({ deep, userTags }) {
const inf = deep.infra;
if (!inf) return <Empty title="Нет данных" />;
return (
<div className="col g-14">
{/* Интернет */}
{inf.internet && inf.internet.providers && (
<Card padding={14}>
<div className="eyebrow mb-10">домашний интернет</div>
{inf.internet.providers.map(p => (
<div key={p.id} className="mb-12">
<div className="row between baseline">
<span className="serif fs-14">{p.name}</span>
<span className="mono fs-10 t-mute">{p.plans.length} тарифов</span>
</div>
<div className="row g-6 mt-6" style={{ flexWrap: 'wrap' }}>
{p.plans.map((pl, i) => (
<span key={i} className="tag mono" style={{ fontSize: 11 }}>
{pl.mbps} Mbps · {pl.priceLocal} {pl.currency}
</span>
))}
</div>
</div>
))}
{inf.internet.realityCheck && (
<div className="serif-italic fs-12 t-soft mt-8" style={{ lineHeight: 1.5, borderLeft: '2px solid var(--warn)', paddingLeft: 10 }}>
⚠️ {inf.internet.realityCheck}
</div>
)}
</Card>
)}
{/* Мобильный */}
{inf.mobile && inf.mobile.operators && (
<Card padding={14}>
<div className="eyebrow mb-10">мобильный оператор</div>
<div className="col g-6">
{inf.mobile.operators.map(op => {
const tone = op.coverage === 'best' ? 'good' : op.coverage === 'good' ? 'mute' : 'warn';
const label = op.coverage === 'best' ? 'лидер' : op.coverage === 'good' ? 'хороший' : 'бюджет';
return (
<div key={op.id} className="row between baseline">
<span className="fs-13">{op.name} {op.has5G && <span className="tag mono" style={{ fontSize: 10, marginLeft: 4 }}>5G</span>}</span>
<span className={`mono fs-11 t-${tone}`}>{label}</span>
</div>
);
})}
</div>
</Card>
)}
{/* Электричество — critical для prof-it */}
{inf.power && (
<Card padding={14} style={inf.power.reliability === 'unstable' ? { borderLeft: '3px solid var(--warn)' } : null}>
<div className="row between center">
<span className="eyebrow">электроснабжение</span>
<span className={`mono fs-11 t-${inf.power.reliability === 'stable' ? 'good' : inf.power.reliability === 'mostly_stable' ? 'warn' : 'bad'}`}>
{inf.power.reliability === 'stable' ? 'стабильно' : inf.power.reliability === 'mostly_stable' ? 'почти стабильно' : 'нестабильно'}
</span>
</div>
{inf.power.monthlyOutages && <StatRow label="Перебои" value={inf.power.monthlyOutages} />}
{inf.power.lastMajor && <StatRow label="Последний сбой" value={inf.power.lastMajor} />}
{inf.power.mitigations && (
<>
<div className="eyebrow mt-12 mb-6">что иметь удалёнщику</div>
<ul className="col g-4" style={{ margin: 0, paddingLeft: 16 }}>
{inf.power.mitigations.map((m, i) => (
<li key={i} className="fs-12 t-soft">{m}</li>
))}
</ul>
</>
)}
</Card>
)}
{/* Транспорт */}
{inf.transport && (
<Card padding={14}>
<div className="eyebrow mb-10">транспорт</div>
{inf.transport.withinCity && <StatRow label="Внутри города" value={inf.transport.withinCity} />}
{inf.transport.toHub && (
<div className="row between baseline mt-6">
<span className="fs-13 t-soft">До {inf.transport.toHub.name}</span>
<span className="mono fs-12">{inf.transport.toHub.transport} · {inf.transport.toHub.timeMin} мин · {inf.transport.toHub.costLocal} GEL</span>
</div>
)}
{inf.transport.taxiApps && (
<div className="row between baseline mt-6">
<span className="fs-13 t-soft">Такси</span>
<span className="mono fs-11">{inf.transport.taxiApps.join(', ')}</span>
</div>
)}
{inf.transport.carNote && (
<div className="fs-12 t-soft mt-10" style={{ lineHeight: 1.5 }}>{inf.transport.carNote}</div>
)}
</Card>
)}
<QnaLink
refs={inf.qnaRefs}
label="Ответы по быту"
loc={deep.id}
seed="интернет мобильный сим транспорт такси"
/>
</div>
);
}
// ---------- TAB: СООБЩЕСТВО ----------
function TabCommunity({ deep, userTags }) {
const c = deep.community;
if (!c) return <Empty title="Нет данных" />;
const schools = (c.schools && c.schools.russianLanguage || []).filter(s => audienceMatch(s, userTags));
const showSchools = userTags.length === 0 || userTags.includes('family-children') || userTags.includes('family-large');
return (
<div className="col g-14">
{c.russianSize && (
<Card padding={14}>
<div className="eyebrow mb-8">русскоязычное сообщество</div>
<div className="row between baseline">
<span className="serif fs-22">{c.russianSize.peak[0].toLocaleString()}–{c.russianSize.peak[1].toLocaleString()}</span>
<span className="mono fs-11 t-mute">пик {c.russianSize.peakYear}</span>
</div>
{c.russianSize.currentNote && (
<div className="serif-italic fs-12 t-soft mt-10" style={{ lineHeight: 1.5 }}>{c.russianSize.currentNote}</div>
)}
{c.languageBarrier != null && (
<div className="row between baseline mt-12">
<span className="fs-12 t-soft">Языковой барьер</span>
<span className={`mono fs-13 t-${c.languageBarrier <= 2 ? 'good' : c.languageBarrier <= 3 ? 'warn' : 'bad'}`}>
{c.languageBarrier} / 5
</span>
</div>
)}
</Card>
)}
{/* Telegram-чаты */}
{c.telegram && (
<Card padding={14}>
<div className="eyebrow mb-8">Telegram-чаты</div>
{Object.entries(c.telegram).map(([scope, chats]) => (
<div key={scope} className="mb-10">
<div className="mono fs-10 t-mute mb-6" style={{ textTransform: 'uppercase' }}>{scope}</div>
<div className="col g-4">
{chats.map((ch, i) => (
<div key={i} className="row between baseline">
<span className="mono fs-12 t-accent">{ch.handle}</span>
<span className="fs-11 t-mute" style={{ textAlign: 'right', maxWidth: '60%' }}>{ch.purpose}</span>
</div>
))}
</div>
</div>
))}
</Card>
)}
{/* Школы — только для семей с детьми */}
{showSchools && schools.length > 0 && (
<Card padding={14}>
<div className="eyebrow mb-8">русскоязычные школы</div>
<div className="col g-8 mt-4">
{schools.map(s => (
<div key={s.id} className="card flat" style={{ padding: 10 }}>
<div className="row between baseline">
<span className="serif fs-13">{s.name}</span>
<span className="tag mono" style={{ fontSize: 10 }}>{s.type === 'private' ? 'частная' : s.type === 'state' ? 'государственная' : s.type}</span>
</div>
<div className="row between mt-4 fs-11 mono t-mute">
<span>{s.city}</span>
{s.monthlyUSD && <span className="t-accent">${s.monthlyUSD[0]}–${s.monthlyUSD[1]}/мес</span>}