File size: 43,597 Bytes
2e11b1e
7f709cf
2e11b1e
 
 
7f709cf
 
 
2e11b1e
7f709cf
1fdcdce
7f709cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fdcdce
7f709cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e11b1e
 
 
7f709cf
2e11b1e
7f709cf
2e11b1e
7f709cf
2e11b1e
7f709cf
2e11b1e
 
 
7f709cf
 
 
2e11b1e
7f709cf
 
 
 
 
 
 
 
 
 
 
 
 
 
2e11b1e
7f709cf
2e11b1e
7f709cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e11b1e
 
7f709cf
 
2e11b1e
7f709cf
 
2e11b1e
 
7f709cf
 
 
2e11b1e
7f709cf
 
2e11b1e
 
082fcfc
 
 
7f709cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
082fcfc
7f709cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
082fcfc
7f709cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
082fcfc
7f709cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
082fcfc
2e11b1e
 
1fdcdce
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Gram Seva Mitra</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&family=Noto+Sans+Tamil:wght@400;600;800&display=swap" rel="stylesheet">
<style>
:root{--saf:#FF9933;--grn:#138808;--navy:#0b2a6b;--ink:#1c2b3a}
*{box-sizing:border-box}
html,body{margin:0}
body{font-family:'Poppins','Noto Sans Tamil',system-ui,-apple-system,'Segoe UI',sans-serif;color:var(--ink);min-height:100vh;
  background:radial-gradient(900px 420px at 8% -5%,#ffd6a1 0,transparent 70%),radial-gradient(900px 420px at 95% 105%,#b8e8b2 0,transparent 70%),linear-gradient(180deg,#fff3df 0%,#ffffff 45%,#e9f8e9 100%);background-attachment:fixed}
.flagbar{height:10px;background:linear-gradient(90deg,var(--saf) 0 33.34%,#fff 33.34% 66.67%,var(--grn) 66.67% 100%);box-shadow:0 1px 0 #0002}
.wrap{max-width:1340px;margin:0 auto;padding:14px 16px 24px}

/* header */
.header{display:flex;align-items:center;gap:16px;padding:12px 20px;border-radius:24px;border:3px solid transparent;
  background:linear-gradient(#fff,#fff) padding-box,linear-gradient(90deg,var(--saf),#cfd9f0 50%,var(--grn)) border-box;box-shadow:0 10px 28px #0b2a6b1a}
.logo{width:62px;height:62px;flex:none}
.logo svg{width:100%;height:100%;animation:spin 24s linear infinite}
.title{font-size:30px;font-weight:800;letter-spacing:.5px;line-height:1.1;background:linear-gradient(90deg,#e4730a,var(--navy) 50%,var(--grn));-webkit-background-clip:text;background-clip:text;color:transparent}
.sub{font-size:13px;color:#4a5b6c;margin-top:2px}
.school{margin-left:auto;text-align:right;font-weight:800;font-size:14px;color:var(--navy)}
.school small{display:block;font-weight:500;color:#5b6b7b;font-size:11px}
.lang{display:flex;background:#eef2f8;border-radius:999px;padding:3px;margin-left:10px}
.lang button{border:0;background:transparent;padding:8px 14px;border-radius:999px;font:inherit;font-weight:700;font-size:13px;cursor:pointer;color:#42546a}
.lang button.on{background:linear-gradient(135deg,var(--saf),#ffb45e 45%,#6cc35f 55%,var(--grn));color:#fff;text-shadow:0 1px 2px #0005}

/* board */
.board{display:grid;grid-template-columns:minmax(240px,1fr) minmax(390px,1.35fr) minmax(240px,1fr);gap:16px;margin-top:16px;align-items:start}
.col{display:flex;flex-direction:column;gap:12px}
.colhead{font-weight:800;font-size:13px;letter-spacing:.6px;color:var(--navy);text-transform:uppercase;padding:0 6px}
.colhead small{display:block;font-weight:500;text-transform:none;letter-spacing:0;color:#667}

/* tiles */
.tile{--c:#138808;position:relative;display:flex;gap:12px;align-items:center;background:#fff;border-radius:18px;padding:11px 14px 11px 12px;
  border:2px solid transparent;border-left:9px solid var(--c);box-shadow:0 6px 16px #0b2a6b14;transition:transform .25s,box-shadow .25s,opacity .25s,background .25s}
.tile .ti{width:52px;height:52px;border-radius:15px;display:grid;place-items:center;font-size:29px;flex:none;background:#f3f3f3;background:color-mix(in srgb,var(--c) 16%,#fff)}
.tile .tn{font-weight:800;font-size:15px;color:var(--c);filter:brightness(.82)}
.tile .tt{font-size:13px;font-weight:600;line-height:1.25}
.tile .te{font-size:11.5px;color:#5d6b79;margin-top:2px;line-height:1.3}
.tile .badge{position:absolute;top:-8px;right:-6px;min-width:26px;height:26px;border-radius:13px;display:none;place-items:center;font-size:14px;font-weight:800;color:#fff;box-shadow:0 3px 8px #0003;padding:0 6px}
.board.explore .tile{cursor:pointer}
.board.explore .tile:hover{transform:translateY(-3px);box-shadow:0 12px 24px #0b2a6b26}
.tile.active{transform:scale(1.045);border-color:var(--c);animation:glow 1.1s ease-in-out infinite alternate;z-index:2}
.tile.hit{background:#f1fff0;border-color:#13880833}
.tile.hit .badge{display:grid;background:var(--grn)}
.tile.unk .badge{display:grid;background:var(--saf)}
.tile.dim{opacity:.5;filter:grayscale(.65)}
.tile.dim .badge{display:grid;background:#9aa6b2}
@keyframes glow{from{box-shadow:0 0 0 3px #ff993340,0 10px 22px #0002}to{box-shadow:0 0 0 7px #13880833,0 14px 28px #0003}}

/* stage */
.stage{position:relative;overflow:hidden;background:#ffffffee;border-radius:30px;padding:16px 18px 20px;border:3px solid #fff;box-shadow:0 16px 40px #0b2a6b24}
.stage:before{content:"";position:absolute;inset:0;pointer-events:none;background:linear-gradient(180deg,#ff993330,transparent 32%,transparent 66%,#13880830)}
.stage>*{position:relative}
.picker-title{text-align:center;font-weight:800;font-size:13px;color:var(--navy);margin-bottom:8px}
.picker{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}
.pick{display:flex;flex-direction:column;align-items:center;gap:2px;border:3px solid transparent;border-radius:18px;padding:6px 4px 8px;cursor:pointer;font:inherit;
  background:linear-gradient(#fff,#fff) padding-box,linear-gradient(#e6ecf3,#e6ecf3) border-box;transition:.2s}
.pick:hover{transform:translateY(-3px)}
.pick.active{background:linear-gradient(#fff,#fff) padding-box,linear-gradient(135deg,var(--saf),var(--navy) 50%,var(--grn)) border-box;box-shadow:0 8px 18px #0b2a6b30}
.pick svg{width:58px;height:70px}
.pick b{font-size:12px;color:var(--ink)}
.pick span{font-size:11px;color:#5b6b7b}
.avwrap{position:relative;margin:12px auto 0;width:min(330px,88%);aspect-ratio:300/380}
.halo{position:absolute;left:3%;right:3%;top:3%;aspect-ratio:1;border-radius:50%;background:conic-gradient(var(--saf),#fff,var(--grn),#fff,var(--saf));box-shadow:0 10px 30px #0b2a6b2a}
.halo:after{content:"";position:absolute;inset:8px;border-radius:50%;background:radial-gradient(circle at 50% 35%,#ffffff 55%,#eef6ff)}
.ring{position:absolute;left:3%;right:3%;top:3%;aspect-ratio:1;border-radius:50%;border:3px solid var(--saf);opacity:0;pointer-events:none}
.ring.r2{border-color:var(--grn);animation-delay:.7s!important}
.speaking .halo{animation:spin 7s linear infinite}
.speaking .ring{animation:ring 1.5s ease-out infinite}
.listening .ring{animation:ring 1.1s ease-out infinite;border-color:#e53935}
@keyframes ring{0%{transform:scale(1);opacity:.7}100%{transform:scale(1.28);opacity:0}}
@keyframes spin{to{transform:rotate(360deg)}}
.avatar-host{position:absolute;inset:0}
.avatar-host svg{width:100%;height:100%;display:block;filter:drop-shadow(0 8px 6px #0002)}
.namebar{text-align:center;margin-top:4px}
.namebar .nm{font-weight:800;font-size:18px;color:var(--navy)}
.status{display:inline-block;margin-top:4px;padding:5px 14px;border-radius:999px;font-weight:700;font-size:12.5px;background:#e7f6e8;color:#14672a}
.listening .status{background:#ffe7e5;color:#b3261e}
.speaking .status{background:#fff0dc;color:#a35a00}
.wave{display:flex;justify-content:center;gap:4px;height:22px;align-items:flex-end;margin-top:6px}
.wave span{width:5px;height:5px;border-radius:3px;background:linear-gradient(var(--saf),var(--grn));transition:height .2s}
.speaking .wave span{animation:wv .7s ease-in-out infinite alternate}
.wave span:nth-child(2){animation-delay:.1s!important}.wave span:nth-child(3){animation-delay:.25s!important}.wave span:nth-child(4){animation-delay:.05s!important}.wave span:nth-child(5){animation-delay:.3s!important}.wave span:nth-child(6){animation-delay:.15s!important}.wave span:nth-child(7){animation-delay:.2s!important}
@keyframes wv{from{height:4px}to{height:22px}}
.bubble{position:relative;margin-top:14px;background:#fff;border:2px solid #dfe8f3;border-radius:22px;padding:12px 16px;text-align:center;box-shadow:0 8px 20px #0b2a6b16}
.bubble:before{content:"";position:absolute;top:-11px;left:50%;margin-left:-10px;width:18px;height:18px;background:#fff;border-left:2px solid #dfe8f3;border-top:2px solid #dfe8f3;transform:rotate(45deg)}
.q-en{font-size:20px;font-weight:700;line-height:1.3}
.q-ta{font-size:17px;font-weight:600;color:#6a2f9a;margin-top:6px;line-height:1.4}
.progress{height:12px;border-radius:99px;overflow:hidden;margin:14px 0 4px;position:relative;border:1px solid #0b2a6b22;background:linear-gradient(90deg,var(--saf) 0 33.3%,#fff 33.3% 66.6%,var(--grn) 66.6%)}
.progress i{position:absolute;right:0;top:0;bottom:0;width:100%;background:#dfe5ea;transition:width .5s}
.plabel{text-align:center;font-size:11.5px;color:#5b6b7b}
.controls{display:flex;flex-direction:column;align-items:center;gap:10px;margin-top:12px}
.bigbtn{border:0;border-radius:999px;padding:15px 30px;font:inherit;font-weight:800;font-size:18px;color:#fff;cursor:pointer;display:flex;align-items:center;gap:10px;
  background:linear-gradient(135deg,var(--saf),#f7931e 40%,#2e9d1f 60%,var(--grn));box-shadow:0 10px 22px #13880838;text-shadow:0 1px 2px #0004;transition:transform .15s}
.bigbtn:hover{transform:translateY(-2px)}
.bigbtn.rec{background:linear-gradient(135deg,#ef5350,#d32f2f);animation:pulse 1s infinite}
@keyframes pulse{50%{box-shadow:0 0 0 12px #e5393530}}
.transcript{min-height:44px;width:100%;background:#f3f7fb;border-radius:14px;padding:10px 14px;font-size:16px;text-align:center;color:#33475b}
.small-row{display:flex;gap:8px;flex-wrap:wrap;justify-content:center}
.chip{border:0;background:#edf2f7;border-radius:12px;padding:8px 13px;font:inherit;font-size:13px;font-weight:600;cursor:pointer;color:#33475b}
.chip:hover{background:#e0e8f1}
details{width:100%;font-size:13px;color:#4a5b6c;text-align:center}
details summary{cursor:pointer;display:inline-block}
details .row{display:flex;gap:8px;margin-top:8px}
details input{flex:1;border:2px solid #dbe4ee;border-radius:12px;padding:9px 12px;font:inherit}
.warn{display:none;margin-top:10px;background:#fff6df;border-left:5px solid var(--saf);border-radius:12px;padding:10px 12px;font-size:12.5px}

/* results */
.results{margin-top:18px;background:#ffffffee;border-radius:28px;padding:20px;box-shadow:0 14px 36px #0b2a6b1f;border:3px solid transparent;
  background:linear-gradient(#fff,#fff) padding-box,linear-gradient(90deg,var(--saf),#cfd9f0 50%,var(--grn)) border-box}
.results h2{margin:0 0 4px;color:var(--navy)}
.cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:14px;margin-top:12px}
.card{--accent:#138808;background:#fff;border-radius:20px;padding:16px;border-left:8px solid var(--accent);box-shadow:0 8px 20px #0b2a6b18}
.card-top{display:flex;gap:12px;align-items:center}
.card .icon{font-size:42px}
.card h3{margin:0;font-size:17px;line-height:1.25}
.gov{font-size:11px;color:#667;margin-top:2px}
.why{font-weight:700;margin:10px 0 6px;font-size:14px}
.benefit{font-size:13px;color:#46535c}
.link{display:inline-block;margin-top:10px;background:var(--navy);color:#fff;text-decoration:none;padding:9px 14px;border-radius:12px;font-weight:700;font-size:13px}
.note{background:#fff6df;border-left:5px solid var(--saf);padding:12px;border-radius:12px;font-size:13px;margin-top:14px}
.hidden{display:none!important}
.footer{margin-top:18px;text-align:center;font-size:12px;color:#5b6b7b}
.footer:before{content:"";display:block;height:6px;border-radius:6px;margin:0 auto 10px;max-width:420px;background:linear-gradient(90deg,var(--saf) 0 33.3%,#fff 33.3% 66.6%,var(--grn) 66.6%);box-shadow:0 0 0 1px #0b2a6b22}

@media(max-width:1060px){
  .board{grid-template-columns:1fr}
  .stage{order:-1}
  .col{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr))}
  .colhead{grid-column:1/-1}
  .school{display:none}
  .lang{margin-left:auto}
}
@media(max-width:560px){.title{font-size:22px}.q-en{font-size:17px}.q-ta{font-size:15px}.header{padding:10px 12px}}
</style>
</head>
<body>
<div class="flagbar"></div>
<div class="wrap">

  <div class="header">
    <div class="logo" id="chakra"></div>
    <div>
      <div class="title">GRAM SEVA MITRA &nbsp;<span style="font-size:.7em">கிராம சேவா மித்ரா</span></div>
      <div class="sub">Voice-first Government Scheme Discovery Assistant</div>
    </div>
    <div class="school">SUTHUKENY HIGH SCHOOL<small>Mentored by K. M. RAMYASRI, PST</small></div>
    <div class="lang" title="Speaking language / பேசும் மொழி">
      <button id="langEn" class="on">English</button><button id="langTa">தமிழ்</button>
    </div>
  </div>

  <div id="board" class="board explore">
    <div class="col" id="colL"><div class="colhead">Schemes to explore<small>Tap a tile to hear an example / ஒரு அட்டையைத் தட்டவும்</small></div><div id="tilesL" class="col" style="display:contents"></div></div>

    <div id="stage" class="stage">
      <div class="picker-title">Choose your Mitra / உங்கள் மித்ராவை தேர்வு செய்யுங்கள்</div>
      <div id="picker" class="picker"></div>

      <div class="avwrap">
        <div class="halo"></div><div class="ring"></div><div class="ring r2"></div>
        <div id="avatarHost" class="avatar-host"></div>
      </div>
      <div class="namebar">
        <div class="nm" id="avName"></div>
        <div id="status" class="status">Ready / தயாராக உள்ளது</div>
        <div class="wave"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></div>
      </div>

      <div class="bubble">
        <div id="bubEn" class="q-en"></div>
        <div id="bubTa" class="q-ta"></div>
      </div>
      <div id="voiceWarn" class="warn">⚠️ Tamil voice not found on this device. The avatar will still move its lips, but may stay silent. Use Chrome on Windows/Android, or switch to English. / இந்த சாதனத்தில் தமிழ் குரல் இல்லை.</div>

      <div class="progress"><i id="barCover"></i></div>
      <div class="plabel" id="plabel"></div>

      <div class="controls">
        <button id="startBtn" class="bigbtn">▶ Start / தொடங்குங்கள்</button>
        <div id="talkArea" class="hidden" style="width:100%;display:flex;flex-direction:column;align-items:center;gap:10px">
          <button id="micBtn" class="bigbtn">🎤 Speak now / இப்போது பேசுங்கள்</button>
          <div id="transcript" class="transcript">Say Yes / ஆம், No / இல்லை, or I don't know / தெரியாது</div>
          <div class="small-row">
            <button id="againBtn" class="chip">🔊 Repeat / மீண்டும்</button>
          </div>
          <details><summary>⌨️ Can't speak? Type your answer / தட்டச்சு செய்யவும்</summary>
            <div class="row"><input id="typed" placeholder="yes / no / don't know"><button id="typedGo" class="chip">OK</button></div>
          </details>
        </div>
      </div>
    </div>

    <div class="col" id="colR"><div class="colhead">More schemes<small>Your answers light these up / உங்கள் பதில்கள் இவற்றை ஒளிரச்செய்யும்</small></div><div id="tilesR" class="col" style="display:contents"></div></div>
  </div>

  <div id="results" class="results hidden">
    <h2>🌾 Schemes you may want to check / நீங்கள் சரிபார்க்கக்கூடிய திட்டங்கள்</h2>
    <p id="resultIntro"></p>
    <div id="cards" class="cards"></div>
    <div class="note">ℹ️ These are <b>possible matches, not a final eligibility decision</b>. Verify eligibility, documents and current rules on the official Government of India website.</div>
    <div style="text-align:center;margin-top:16px"><button id="restart" class="bigbtn" style="margin:auto">🔄 Start again / மீண்டும் தொடங்குங்கள்</button></div>
  </div>

  <div class="footer">School-level awareness prototype • Official Government of India links only • No Aadhaar, OTP, bank or other sensitive information is requested.</div>
</div>

<!-- __DATA_SCRIPT__ -->

<script>
(function(){
'use strict';
var dataEl=document.getElementById('app-data');
if(!dataEl){document.body.insertAdjacentHTML('afterbegin','<p style="padding:20px">app-data missing</p>');return;}
var DATA=JSON.parse(dataEl.textContent);
var $=function(id){return document.getElementById(id)};

/* ---------- content that is only needed by the tiles ---------- */
var TILE={
 pregnant:{short:'PMMVY',tag:['Maternity support','தாய்மை நிதியுதவி'],ex:['e.g. a pregnant mother in the family','எ.கா. குடும்பத்தில் கர்ப்பிணித் தாய்']},
 oldage:{short:'IGNOAPS',tag:['Old-age pension','முதியோர் ஓய்வூதியம்'],ex:['e.g. a grandparent who needs support','எ.கா. உதவி தேவைப்படும் தாத்தா / பாட்டி']},
 widow:{short:'IGNWPS',tag:['Widow pension','விதவை ஓய்வூதியம்'],ex:['e.g. a widowed mother or aunt','எ.கா. கணவரை இழந்த அம்மா / அத்தை']},
 disability:{short:'ADIP',tag:['Aids for disability','மாற்றுத்திறன் உதவி சாதனங்கள்'],ex:['e.g. wheelchair, hearing aid','எ.கா. சக்கர நாற்காலி, செவிப்புலன் கருவி']},
 farmer:{short:'PM-KISAN',tag:['Farmer income support','விவசாயி வருமான ஆதரவு'],ex:['e.g. family owns farm land','எ.கா. குடும்பத்திற்கு விவசாய நிலம் உள்ளது']},
 housing:{short:'PMAY-G',tag:['Rural housing','கிராமப்புற வீடு'],ex:['e.g. a permanent house for the family','எ.கா. குடும்பத்திற்கு நிரந்தர வீடு']},
 health:{short:'PM-JAY',tag:['Health cover','மருத்துவ பாதுகாப்பு'],ex:['e.g. help with hospital treatment','எ.கா. மருத்துவமனை சிகிச்சைக்கு உதவி']},
 lpg:{short:'PMUY',tag:['LPG gas connection','LPG எரிவாயு இணைப்பு'],ex:['e.g. a gas stove instead of firewood','எ.கா. விறகு அடுப்புக்குப் பதிலாக எரிவாயு']},
 bank:{short:'PMJDY',tag:['Basic bank account','அடிப்படை வங்கி கணக்கு'],ex:['e.g. a zero-balance account','எ.கா. பூஜ்ய இருப்பு கணக்கு']},
 student:{short:'NSP',tag:['Scholarships','கல்வி உதவித்தொகை'],ex:['e.g. a school or college student','எ.கா. பள்ளி / கல்லூரி மாணவர்']}
};
var COLORS={pink:'#e83e8c',gold:'#d99b00',violet:'#7952b3',blue:'#2589bd',green:'#138808',orange:'#ff7a00',red:'#d93025',teal:'#008c95',indigo:'#405de6',purple:'#8e44ad'};
var GREET={en:"Hello! I am your Mitra. Let's find government schemes that may help your family.",ta:'வணக்கம்! நான் உங்கள் மித்ரா. உங்கள் குடும்பத்திற்கு உதவக்கூடிய அரசு திட்டங்களைக் கண்டறிவோம்.'};

/* ---------- state ---------- */
var L=(navigator.language||'').toLowerCase().indexOf('ta')===0?'ta':'en';
var avatar=DATA.avatars[0], qi=0, answers={}, started=false, finished=false, listening=false, rec=null, retries=0, exploreKind=null;
var schemeBy={}; DATA.schemes.forEach(function(s){schemeBy[s.trigger[0]]=s;});
var tiles=DATA.questions.filter(function(q){return schemeBy[q.kind]});
function isMatch(kind,a){return (kind==='lpg'||kind==='bank')?a==='no':a==='yes';}

/* ---------- Ashoka-chakra style logo ---------- */
(function(){
  var s='<svg viewBox="0 0 100 100"><circle cx="50" cy="50" r="46" fill="#fff" stroke="#0b2a6b" stroke-width="4"/><circle cx="50" cy="50" r="6" fill="#0b2a6b"/>';
  for(var i=0;i<24;i++){var a=i*Math.PI/12;s+='<line x1="'+(50+8*Math.cos(a))+'" y1="'+(50+8*Math.sin(a))+'" x2="'+(50+42*Math.cos(a))+'" y2="'+(50+42*Math.sin(a))+'" stroke="#0b2a6b" stroke-width="2"/>';}
  $('chakra').innerHTML=s+'<circle cx="50" cy="50" r="46" fill="none" stroke="#FF9933" stroke-width="2" stroke-dasharray="6 6"/></svg>';
})();

/* ---------- avatar drawing ---------- */
var LOOK={
 man:{skin:'#d9a273',dk:'#bf8858',hair:'#1a1a1e',iris:'#3f2615'},
 woman:{skin:'#e6b189',dk:'#cf966c',hair:'#171010',iris:'#4a2c17'},
 girl:{skin:'#e9b690',dk:'#d39b72',hair:'#2a1710',iris:'#4a2c17',kid:true},
 boy:{skin:'#d3976a',dk:'#bb7f53',hair:'#14110f',iris:'#3f2615',kid:true}
};
function avatarSVG(key,p){
  var k=LOOK[key]||LOOK.man, kid=!!k.kid;
  var hx=kid?66:62, hy=kid?70:74, ey=kid?152:146, ex=kid?27:28, er=kid?13:11.5, my=kid?196:198;
  var sk=k.skin, dk=k.dk, hr=k.hair;
  function eye(id,cx){
    return '<g id="'+p+id+'"><ellipse cx="'+cx+'" cy="'+ey+'" rx="'+er+'" ry="'+(er*1.08)+'" fill="#fff" stroke="#0002" stroke-width="1"/>'+
    '<g id="'+p+id+'i"><circle cx="'+cx+'" cy="'+ey+'" r="'+(er*.64)+'" fill="'+k.iris+'"/><circle cx="'+cx+'" cy="'+ey+'" r="'+(er*.34)+'" fill="#0d0d0d"/><circle cx="'+(cx-er*.26)+'" cy="'+(ey-er*.3)+'" r="'+(er*.17)+'" fill="#fff"/></g>'+
    '<path d="M '+(cx-er)+' '+(ey-1)+' Q '+cx+' '+(ey-er*1.55)+' '+(cx+er)+' '+(ey-1)+'" fill="none" stroke="#15110f" stroke-width="2.6" stroke-linecap="round"/></g>'+
    '<path id="'+p+id+'l" d="M '+(cx-er)+' '+ey+' Q '+cx+' '+(ey+4)+' '+(cx+er)+' '+ey+'" fill="none" stroke="#15110f" stroke-width="2.8" stroke-linecap="round" opacity="0"/>';
  }
  /* body / clothes */
  var shoulder='M26 380 Q34 284 106 270 L194 270 Q266 284 274 380 Z', body='';
  if(key==='man'){
    body='<path d="'+shoulder+'" fill="#fbfbfb" stroke="#d5d9de" stroke-width="2"/>'+
    '<path d="M126 270 L150 318 L174 270 Z" fill="'+dk+'"/>'+
    '<g stroke="none"><path d="M88 272 Q150 306 212 272 L222 292 Q150 330 78 292 Z" fill="#FF9933"/>'+
    '<path d="M78 292 Q150 330 222 292 L230 312 Q150 352 70 312 Z" fill="#ffffff" stroke="#d5d9de" stroke-width="1.5"/>'+
    '<path d="M70 312 Q150 352 230 312 L238 332 Q150 374 62 332 Z" fill="#138808"/></g>'+
    '<circle cx="150" cy="333" r="7" fill="none" stroke="#0b2a6b" stroke-width="1.6"/><circle cx="150" cy="333" r="1.6" fill="#0b2a6b"/>';
  }else if(key==='woman'){
    body='<path d="'+shoulder+'" fill="#138808"/>'+
    '<path d="M118 270 Q150 312 182 270 Z" fill="'+sk+'"/>'+
    '<path d="M176 270 L214 272 Q262 290 274 380 L204 380 Q206 310 176 270 Z" fill="#FF9933"/>'+
    '<path d="M190 272 L214 274 Q258 292 268 380 L252 380 Q244 304 190 272Z" fill="#ffffff" opacity=".9"/>'+
    '<path d="M30 340 Q150 366 270 340 L274 380 L26 380Z" fill="#0f6e06"/><path d="M28 352 Q150 378 272 352" stroke="#FF9933" stroke-width="5" fill="none"/>';
  }else if(key==='girl'){
    body='<path d="'+shoulder+'" fill="#FF9933"/>'+
    '<path d="M112 270 Q150 306 188 270 L176 270 Q150 292 124 270Z" fill="#fff"/>'+
    '<path d="M118 270 Q150 300 182 270 Z" fill="'+sk+'"/>'+
    '<g transform="translate(150 300)"><path d="M0 0 L-28 -14 L-28 14Z" fill="#138808"/><path d="M0 0 L28 -14 L28 14Z" fill="#138808"/><circle r="6" fill="#0b8a00" stroke="#fff" stroke-width="2"/></g>'+
    '<path d="M26 352 Q150 378 274 352 L274 380 L26 380Z" fill="#fff" opacity=".85"/>';
  }else{
    body='<path d="'+shoulder+'" fill="#ffffff" stroke="#d5d9de" stroke-width="2"/>'+
    '<path d="M112 270 L150 316 L188 270 L172 266 L150 296 L128 266Z" fill="#138808"/>'+
    '<path d="M118 270 L150 312 L182 270Z" fill="'+dk+'"/>'+
    '<path d="M144 304 L156 304 L160 352 L150 364 L140 352Z" fill="#FF9933"/>'+
    '<path d="M40 380 Q46 330 70 300" stroke="#138808" stroke-width="5" fill="none"/><path d="M260 380 Q254 330 230 300" stroke="#138808" stroke-width="5" fill="none"/>';
  }
  /* hair (back) */
  var hairBack='', hairFront='', extra='';
  if(key==='woman'){
    hairBack='<ellipse cx="150" cy="142" rx="72" ry="84" fill="'+hr+'"/>'+
      '<path d="M80 140 Q58 210 70 305 Q96 316 112 292 Q100 214 106 150Z" fill="'+hr+'"/>'+
      '<path d="M220 140 Q242 210 230 305 Q204 316 188 292 Q200 214 194 150Z" fill="'+hr+'"/>';
    hairFront='<path d="M84 152 Q74 64 150 62 Q226 64 216 152 Q208 104 150 98 Q92 104 84 152Z" fill="'+hr+'"/><path d="M150 62 Q148 84 146 100" stroke="#ffffff22" stroke-width="2" fill="none"/>';
    extra='<circle cx="150" cy="113" r="3.8" fill="#d32f2f"/><path d="M92 86 q8 -14 24 -10 q-4 12 -24 10z" fill="#fff"/><circle cx="104" cy="82" r="3" fill="#FF9933"/>';
  }else if(key==='girl'){
    hairBack='<path d="M96 108 Q40 118 48 196 Q58 238 82 206 Q88 160 104 132Z" fill="'+hr+'"/><path d="M204 108 Q260 118 252 196 Q242 238 218 206 Q212 160 196 132Z" fill="'+hr+'"/><ellipse cx="150" cy="140" rx="70" ry="76" fill="'+hr+'"/>';
    hairFront='<path d="M84 154 Q76 74 150 70 Q224 74 216 154 Q208 112 150 106 Q92 112 84 154Z" fill="'+hr+'"/><path d="M98 118 Q128 134 150 108 Q172 134 202 118 Q196 100 150 98 Q104 100 98 118Z" fill="'+hr+'"/>'+
      '<g><circle cx="90" cy="112" r="9" fill="#138808"/><circle cx="210" cy="112" r="9" fill="#138808"/><circle cx="90" cy="112" r="3.5" fill="#fff"/><circle cx="210" cy="112" r="3.5" fill="#fff"/></g>';
    extra='<circle cx="150" cy="104" r="3" fill="#d32f2f" opacity="0"/>';
  }else if(key==='boy'){
    hairBack='<ellipse cx="150" cy="140" rx="68" ry="76" fill="'+hr+'"/>';
    hairFront='<path d="M86 150 Q80 72 150 70 Q220 72 214 150 Q208 118 176 110 Q132 100 98 120 Q90 130 86 150Z" fill="'+hr+'"/>';
  }else{
    hairBack='<ellipse cx="150" cy="140" rx="66" ry="80" fill="'+hr+'"/>';
    hairFront='<path d="M86 152 Q78 66 150 64 Q222 66 214 152 Q206 106 150 100 Q94 106 86 152Z" fill="'+hr+'"/>';
    extra='<path d="M126 '+(my-12)+' Q150 '+(my-22)+' 174 '+(my-12)+' Q160 '+(my-4)+' 150 '+(my-9)+' Q140 '+(my-4)+' 126 '+(my-12)+'Z" fill="'+hr+'"/>';
  }
  var mouth='<g id="'+p+'mouth" transform="translate(150 '+my+')">'+
    '<path id="'+p+'smile" d="M -16 -2 Q 0 12 16 -2" fill="none" stroke="#8f3a3a" stroke-width="3.2" stroke-linecap="round"/>'+
    '<g id="'+p+'open" style="display:none"><clipPath id="'+p+'mc"><path id="'+p+'mcp" d=""/></clipPath>'+
    '<path id="'+p+'mo" d="" fill="#5b1220" stroke="#b34452" stroke-width="2.4" stroke-linejoin="round"/>'+
    '<g clip-path="url(#'+p+'mc)"><path id="'+p+'teeth" d="" fill="#fff"/><ellipse id="'+p+'tongue" cx="0" cy="0" rx="8" ry="4" fill="#e8737f"/></g></g></g>';
  return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 380" role="img" aria-label="'+key+' avatar">'+
    '<rect x="128" y="200" width="44" height="76" rx="16" fill="'+dk+'"/>'+body+
    '<g id="'+p+'H">'+hairBack+
      '<circle cx="'+(150-hx)+'" cy="158" r="11" fill="'+sk+'"/><circle cx="'+(150+hx)+'" cy="158" r="11" fill="'+sk+'"/>'+
      '<circle cx="'+(150-hx)+'" cy="158" r="5" fill="'+dk+'" opacity=".5"/><circle cx="'+(150+hx)+'" cy="158" r="5" fill="'+dk+'" opacity=".5"/>'+
      '<ellipse cx="150" cy="150" rx="'+hx+'" ry="'+hy+'" fill="'+sk+'"/>'+
      '<ellipse cx="'+(150-ex-10)+'" cy="'+(my-14)+'" rx="13" ry="8" fill="#f06b6b" opacity="'+(key==='man'?'.12':'.3')+'"/><ellipse cx="'+(150+ex+10)+'" cy="'+(my-14)+'" rx="13" ry="8" fill="#f06b6b" opacity="'+(key==='man'?'.12':'.3')+'"/>'+
      eye('eL',150-ex)+eye('eR',150+ex)+
      '<g id="'+p+'brows" stroke="'+hr+'" stroke-width="'+(kid?3.6:4.6)+'" stroke-linecap="round" fill="none"><path d="M '+(150-ex-12)+' '+(ey-24)+' Q '+(150-ex)+' '+(ey-31)+' '+(150-ex+12)+' '+(ey-24)+'"/><path d="M '+(150+ex-12)+' '+(ey-24)+' Q '+(150+ex)+' '+(ey-31)+' '+(150+ex+12)+' '+(ey-24)+'"/></g>'+
      '<path d="M 146 '+(ey+10)+' Q 141 '+(ey+30)+' 146 '+(ey+33)+' Q 150 '+(ey+36)+' 155 '+(ey+33)+'" fill="none" stroke="'+dk+'" stroke-width="3" stroke-linecap="round"/>'+
      extra+mouth+hairFront+
    '</g></svg>';
}

/* ---------- animation engine ---------- */
var R={}, P='m_';
var S={speaking:false,listening:false,mo:0,mw:15,to:0,tw:15,nv:0,pulse:0,bt:1500,bp:-1,et:0,etx:0,ety:0,ex:0,ey:0};
var VIS=[[.95,15],[.6,18],[.4,9.5],[.15,19],[.8,12],[0,15],[.3,13],[.7,10],[.5,8.5]];
function mountAvatar(){
  $('avatarHost').innerHTML=avatarSVG(avatar.id,P);
  ['H','brows','eL','eR','eLi','eRi','eLl','eRl','smile','open','mo','mcp','teeth','tongue'].forEach(function(id){R[id]=document.getElementById(P+id);});
}
function mouthPath(o,w){
  var up=2+o*3, dn=o*22+1;
  return 'M '+(-w)+' 0 Q '+(-w*.5)+' '+(-up)+' 0 '+(-up*.6)+' Q '+(w*.5)+' '+(-up)+' '+w+' 0 Q '+(w*.6)+' '+dn+' 0 '+dn+' Q '+(-w*.6)+' '+dn+' '+(-w)+' 0 Z';
}
var last=performance.now();
function frame(t){
  var dt=Math.min(60,Math.max(1,t-last)); last=t;
  if(R.H){
    /* blink */
    var bs=1;
    if(S.bp<0 && t>S.bt) S.bp=0;
    if(S.bp>=0){S.bp+=dt/150;
      if(S.bp>=1){S.bp=-1;S.bt=t+(Math.random()<.2?240:1800+Math.random()*3400);}
      else bs=1-.93*Math.sin(Math.PI*S.bp);}
    /* eye wander */
    if(t>S.et){var f=S.speaking?.4:1;S.etx=(Math.random()-.5)*5*f;S.ety=(Math.random()-.5)*3*f;S.et=t+1200+Math.random()*2800;}
    var ke=Math.min(1,dt/80);S.ex+=(S.etx-S.ex)*ke;S.ey+=(S.ety-S.ey)*ke;
    /* mouth */
    if(S.speaking){
      if(t>S.nv){var v=VIS[(Math.random()*VIS.length)|0];S.to=v[0];S.tw=v[1];S.nv=t+65+Math.random()*95;}
      if(S.pulse>0){S.to=Math.max(S.to,.55+.4*S.pulse);S.pulse=Math.max(0,S.pulse-dt/160);}
    }else{S.to=0;S.tw=15;}
    var km=Math.min(1,dt/40);S.mo+=(S.to-S.mo)*km;S.mw+=(S.tw-S.mw)*km;
    /* head + brows */
    var deg=S.speaking?Math.sin(t/430)*1.7+Math.sin(t/260)*.8:(S.listening?3.5+Math.sin(t/900)*.6:Math.sin(t/1500)*.7);
    var dy=Math.sin(t/950)*1.3;
    var brow=(S.listening?-3:0)+(-3.5*S.mo);
    R.H.setAttribute('transform','translate(0 '+(dy+16).toFixed(2)+') rotate('+deg.toFixed(2)+' 150 272)');
    R.brows.setAttribute('transform','translate(0 '+brow.toFixed(2)+')');
    /* eyes */
    ['L','R'].forEach(function(s){
      var g=R['e'+s], ey=g.getBBox?null:null;
    });
    setBlink(R.eL,R.eLl,bs);setBlink(R.eR,R.eRl,bs);
    R.eLi.setAttribute('transform','translate('+S.ex.toFixed(2)+' '+S.ey.toFixed(2)+')');
    R.eRi.setAttribute('transform','translate('+S.ex.toFixed(2)+' '+S.ey.toFixed(2)+')');
    /* mouth drawing */
    if(S.mo<.07){R.smile.style.display='';R.open.style.display='none';}
    else{
      R.smile.style.display='none';R.open.style.display='';
      var d=mouthPath(S.mo,S.mw);R.mo.setAttribute('d',d);R.mcp.setAttribute('d',d);
      var up=2+S.mo*3, dn=S.mo*22+1, th=Math.min(6,dn*.45), w=S.mw;
      R.teeth.setAttribute('d','M '+(-w*.75)+' '+(-up*.5)+' L '+(w*.75)+' '+(-up*.5)+' L '+(w*.65)+' '+th+' L '+(-w*.65)+' '+th+' Z');
      R.tongue.setAttribute('cy',(dn*.82).toFixed(1));R.tongue.setAttribute('rx',(w*.5).toFixed(1));R.tongue.setAttribute('ry',(dn*.3+.5).toFixed(1));
    }
  }
  requestAnimationFrame(frame);
}
var EYE_Y=null;
function setBlink(g,lid,s){
  if(!g)return;
  var y=+g.firstChild.getAttribute('cy');
  g.setAttribute('transform','translate(0 '+y+') scale(1 '+s.toFixed(3)+') translate(0 '+(-y)+')');
  lid.setAttribute('opacity',(1-s)>.5?1:0);
}

/* ---------- speech out ---------- */
var spkId=0, spkTimers=[];
function pickVoice(lang,profile){
  var vs=window.speechSynthesis?speechSynthesis.getVoices():[];
  var pool=vs.filter(function(v){return v.lang.toLowerCase().replace('_','-').indexOf(lang==='ta'?'ta':'en')===0;});
  if(!pool.length)return null;
  var pref=pool.filter(function(v){return /(en|ta)-in/i.test(v.lang.replace('_','-'));});
  var list=pref.length?pref:pool;
  var fem=/(female|woman|zira|heera|kalpana|pallavi|neerja|samantha|swara|priya|veena|aria|jenny)/i, mal=/(male|man|david|ravi|valluvar|prabhat|hemant|mark|guy)/i;
  var wantF=(profile==='female'||profile==='girl');
  return list.filter(function(v){return wantF?fem.test(v.name):(!fem.test(v.name)&&mal.test(v.name));})[0]||list[0];
}
function setSpeaking(v){
  S.speaking=v;$('stage').classList.toggle('speaking',v);
  if(!listening) setStatus(v?'speak':'ready');
}
function clearSpk(){spkTimers.forEach(clearTimeout);spkTimers=[];}
function stopSpeak(){spkId++;clearSpk();if('speechSynthesis' in window)speechSynthesis.cancel();setSpeaking(false);}
function speak(text,lang,done){
  stopSpeak();
  var id=spkId, started=false, finished=false;
  var est=Math.max(1600,text.length*(lang==='ta'?85:62));
  function finish(){if(finished||id!==spkId)return;finished=true;clearSpk();setSpeaking(false);if(done)done();}
  function simulate(){if(id!==spkId||finished)return;clearSpk();if('speechSynthesis' in window)speechSynthesis.cancel();spkTimers.push(setTimeout(finish,est));}
  setSpeaking(true);
  if(!('speechSynthesis' in window)){simulate();return;}
  var u=new SpeechSynthesisUtterance(text);
  u.lang=lang==='ta'?'ta-IN':'en-IN';
  var v=pickVoice(lang,avatar.voice);if(v)u.voice=v;
  u.rate=.92;u.pitch={girl:1.35,boy:1.2,female:1.08,male:.9}[avatar.voice]||1;
  u.onstart=function(){started=true;clearSpk();spkTimers.push(setTimeout(finish,est*3+4000));};
  u.onboundary=function(){S.pulse=1;};
  u.onend=finish;
  u.onerror=function(){if(!started)simulate();else finish();};
  spkTimers.push(setTimeout(function(){if(!started)simulate();},2000));
  setTimeout(function(){if(id===spkId)speechSynthesis.speak(u);},70);
}
function checkVoiceWarn(){
  var vs=window.speechSynthesis?speechSynthesis.getVoices():[];
  var has=vs.some(function(v){return v.lang.toLowerCase().replace('_','-').indexOf('ta')===0;});
  $('voiceWarn').style.display=(L==='ta'&&vs.length&&!has)?'block':'none';
}
if('speechSynthesis' in window)speechSynthesis.onvoiceschanged=checkVoiceWarn;

/* ---------- ui helpers ---------- */
function setStatus(k){
  var m={ready:'Ready / தயாராக உள்ளது',speak:'Speaking / பேசுகிறது…',listen:'Listening / கேட்கிறது…'};
  $('status').textContent=m[k]||m.ready;
}
function setBubble(en,ta){$('bubEn').textContent=en;$('bubTa').textContent=ta;}
function renderPicker(){
  $('picker').innerHTML=DATA.avatars.map(function(a,i){
    return '<button class="pick'+(a.id===avatar.id?' active':'')+'" data-i="'+i+'">'+avatarSVG(a.id,'t'+i+'_')+'<b>'+a.label+'</b><span>'+a.ta+'</span></button>';
  }).join('');
  Array.prototype.forEach.call($('picker').querySelectorAll('.pick'),function(b){
    b.onclick=function(){
      avatar=DATA.avatars[+b.dataset.i];
      renderPicker();mountAvatar();$('avName').textContent=avatar.label+' / '+avatar.ta;
      if(started&&!finished){speakQuestion();}
      else if(!started){setBubble(GREET.en,GREET.ta);speak(GREET[L],L);}
    };
  });
}
function tileHTML(q){
  var s=schemeBy[q.kind],t=TILE[q.kind]||{short:s.name_en,tag:[s.name_en,s.name_ta],ex:['','']};
  var li=L==='ta'?1:0;
  return '<div class="tile" data-kind="'+q.kind+'" style="--c:'+(COLORS[s.theme]||'#138808')+'"><div class="badge"></div><div class="ti">'+s.icon+'</div>'+
    '<div class="tb"><div class="tn">'+t.short+'</div><div class="tt">'+t.tag[li]+'</div><div class="te">'+t.ex[li]+'</div></div></div>';
}
function renderTiles(){
  var h=Math.ceil(tiles.length/2);
  $('tilesL').innerHTML=tiles.slice(0,h).map(tileHTML).join('');
  $('tilesR').innerHTML=tiles.slice(h).map(tileHTML).join('');
  Array.prototype.forEach.call(document.querySelectorAll('.tile'),function(el){el.onclick=function(){exploreTile(el.dataset.kind);};});
  updateTiles();
}
function updateTiles(){
  var cur=(started&&!finished&&DATA.questions[qi])?DATA.questions[qi].kind:exploreKind;
  Array.prototype.forEach.call(document.querySelectorAll('.tile'),function(el){
    var k=el.dataset.kind,a=answers[k],b=el.querySelector('.badge');
    el.className='tile';
    if(a){
      if(a==='unknown'){el.classList.add('unk');b.textContent='?';}
      else if(isMatch(k,a)){el.classList.add('hit');b.textContent='✓';}
      else{el.classList.add('dim');b.textContent='–';}
    }
    if(k===cur)el.classList.add('active');
  });
  $('board').classList.toggle('explore',!started||finished);
}
function exploreTile(kind){
  if(started&&!finished)return;
  var s=schemeBy[kind];if(!s)return;
  exploreKind=kind;updateTiles();
  setBubble(s.name_en+' — '+s.why_en,s.name_ta+' — '+s.why_ta);
  speak(L==='ta'?s.why_ta:s.why_en,L,function(){exploreKind=null;updateTiles();});
}
function setProgress(){
  var n=DATA.questions.length,p=finished?100:Math.round(qi/n*100);
  $('barCover').style.width=(100-p)+'%';
  $('plabel').textContent=finished?'Done / முடிந்தது':(started?('Question '+(qi+1)+' of '+n+' / கேள்வி '+(qi+1)+' / '+n):'');
}

/* ---------- flow ---------- */
function speakQuestion(auto){
  var q=DATA.questions[qi];if(!q)return;
  speak(L==='ta'?q.ta:q.en,L,function(){if(auto!==false)startListening();});
}
function showQuestion(){
  if(qi>=DATA.questions.length){finish();return;}
  var q=DATA.questions[qi];retries=0;
  setBubble(q.en,q.ta);setProgress();updateTiles();
  $('transcript').textContent="Say Yes / ஆம், No / இல்லை, or I don't know / தெரியாது";
  setTimeout(speakQuestion,250);
}
function normalize(raw){
  var s=(raw||'').toLowerCase().trim();if(!s)return null;
  if(/don'?t know|do not know|not sure|no idea|dunno|maybe/.test(s)||/தெரியாது|தெரியல|தெரியவில்லை|theriyadhu|theriyathu/.test(s))return 'unknown';
  if(/\b(no|nope|nah|not)\b/.test(s)||/இல்லை|இல்ல|கிடையாது|வேண்டாம்|illai|illa\b|ila\b/.test(s))return 'no';
  if(/\b(yes|yeah|yep|yup|correct|right|sure|ok|okay)\b/.test(s)||/ஆம்|ஆமாம்|ஆமா|உண்டு|இருக்கிறது|இருக்கு|இருக்காங்க|இருக்கிறார்|வேண்டும்|வேணும்|aam|amam|aama/.test(s))return 'yes';
  return null;
}
function handleSpeech(text){
  $('transcript').textContent='“'+text+'”';
  var ans=normalize(text);
  if(!ans){
    retries++;
    var msg=L==='ta'?'மன்னிக்கவும். ஆம், இல்லை அல்லது தெரியாது என்று சொல்லுங்கள்.':"Sorry. Please say Yes, No, or I don't know.";
    if(retries<=2)speak(msg,L,function(){startListening();});else speak(msg,L);
    return;
  }
  answers[DATA.questions[qi].kind]=ans;updateTiles();
  setTimeout(function(){qi++;showQuestion();},700);
}
function finish(){
  finished=true;stopSpeak();setProgress();updateTiles();
  $('results').classList.remove('hidden');
  var matched=DATA.schemes.filter(function(s){var a=answers[s.trigger[0]];return a&&isMatch(s.trigger[0],a);});
  var intro=L==='ta'?('உங்கள் பதில்களின் அடிப்படையில் '+matched.length+' திட்டங்களை சரிபார்க்கலாம்.'):('Based on your answers, '+matched.length+' scheme(s) may be worth checking.');
  $('resultIntro').textContent=intro;
  setBubble('Based on your answers, '+matched.length+' scheme(s) may be worth checking.','உங்கள் பதில்களின் அடிப்படையில் '+matched.length+' திட்டங்களை சரிபார்க்கலாம்.');
  $('cards').innerHTML=matched.length?matched.map(function(s){
    return '<div class="card" style="--accent:'+(COLORS[s.theme]||'#138808')+'"><div class="card-top"><div class="icon">'+s.icon+'</div><div><h3>'+(L==='ta'?s.name_ta:s.name_en)+'</h3><div class="gov">'+s.source+'</div></div></div>'+
      '<div class="why">'+(L==='ta'?s.why_ta:s.why_en)+'</div><div class="benefit">'+(L==='ta'?s.benefit_ta:s.benefit_en)+'</div>'+
      '<a class="link" href="'+s.url+'" target="_blank" rel="noopener noreferrer">🌐 Official Government Website</a></div>';
  }).join(''):'<div class="card"><h3>'+(L==='ta'?'மேலும் தகவல் தேவை':'More information may be needed')+'</h3><div class="benefit">'+(L==='ta'?'பெற்றோர் அல்லது ஆசிரியரிடம் மேலும் தகவல் கேட்டு மீண்டும் முயற்சிக்கலாம்.':'Ask a parent or teacher for more information and try again.')+'</div></div>';
  speak(intro,L);
  setTimeout(function(){$('results').scrollIntoView({behavior:'smooth',block:'start'});},400);
}

/* ---------- speech in ---------- */
function micUI(on){
  listening=on;S.listening=on;$('stage').classList.toggle('listening',on);
  var b=$('micBtn');b.classList.toggle('rec',on);
  b.textContent=on?'🔴 Listening… / கேட்கிறது…':'🎤 Speak now / இப்போது பேசுங்கள்';
  if(on)setStatus('listen');else setStatus(S.speaking?'speak':'ready');
}
function startListening(){
  var SR=window.SpeechRecognition||window.webkitSpeechRecognition;
  if(!SR){$('transcript').textContent='Speech recognition is not available here. Use Google Chrome, or type your answer below. / Chrome பயன்படுத்தவும் அல்லது தட்டச்சு செய்யவும்.';return;}
  if(listening){try{rec.stop();}catch(e){}return;}
  stopSpeak();
  rec=new SR();rec.lang=L==='ta'?'ta-IN':'en-IN';rec.interimResults=true;rec.continuous=false;
  var finalText='',got=false;
  rec.onstart=function(){micUI(true);};
  rec.onresult=function(e){
    var t='';for(var i=e.resultIndex;i<e.results.length;i++)t+=e.results[i][0].transcript;
    $('transcript').textContent=t;
    if(e.results[e.results.length-1].isFinal){got=true;finalText=t;}
  };
  rec.onerror=function(ev){
    if(ev.error==='not-allowed'||ev.error==='service-not-allowed')$('transcript').textContent='Microphone blocked. Allow microphone access in the browser, or type your answer. / மைக் அனுமதி தேவை.';
    else if(ev.error==='no-speech')$('transcript').textContent="I didn't hear you. Tap the mic and try again. / கேட்கவில்லை. மைக்கை தட்டி மீண்டும் முயலுங்கள்.";
  };
  rec.onend=function(){micUI(false);if(got)handleSpeech(finalText);};
  try{rec.start();}catch(e){micUI(false);}
}

/* ---------- wiring ---------- */
function setLang(l){
  L=l;$('langEn').classList.toggle('on',l==='en');$('langTa').classList.toggle('on',l==='ta');
  renderTiles();checkVoiceWarn();
  if(started&&!finished)speakQuestion();
}
$('langEn').onclick=function(){setLang('en');};
$('langTa').onclick=function(){setLang('ta');};
$('startBtn').onclick=function(){
  started=true;finished=false;qi=0;answers={};exploreKind=null;
  $('startBtn').classList.add('hidden');$('talkArea').classList.remove('hidden');
  showQuestion();
};
$('micBtn').onclick=startListening;
$('againBtn').onclick=function(){if(started&&!finished)speakQuestion(false);};
$('typedGo').onclick=function(){var v=$('typed').value;if(v&&started&&!finished){stopSpeak();$('typed').value='';handleSpeech(v);}};
$('typed').addEventListener('keydown',function(e){if(e.key==='Enter')$('typedGo').click();});
$('restart').onclick=function(){
  stopSpeak();started=true;finished=false;qi=0;answers={};
  $('results').classList.add('hidden');window.scrollTo({top:0,behavior:'smooth'});showQuestion();
};

/* ---------- boot ---------- */
$('langEn').classList.toggle('on',L==='en');$('langTa').classList.toggle('on',L==='ta');
$('avName').textContent=avatar.label+' / '+avatar.ta;
renderPicker();mountAvatar();renderTiles();setProgress();checkVoiceWarn();
setBubble(GREET.en,GREET.ta);
requestAnimationFrame(frame);
})();
</script>
</body>
</html>