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 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
/**
 * VoiceService - Voice command processing and text-to-speech.
 *
 * Provides:
 *  - Intent recognition from voice transcripts (Hindi + English)
 *  - Advanced intents with entity extraction (crops, locations, dates, diseases)
 *  - ConversationEngine for multi-turn, context-aware dialogues
 *  - Confidence scoring for matched commands
 *  - Voice settings management with localStorage persistence
 *  - Text-to-speech synthesis with configurable rate and voice
 *  - Browser compatibility checks
 *  - Microphone permission management
 *  - Offline support for all client-side command processing
 */

import { LANGUAGES, ROUTES, SUPPORTED_CROPS, STORAGE_KEYS } from "@utils/constants";
import storage from "@utils/storage";

// ---------------------------------------------------------------------------
// Intent Definitions
// ---------------------------------------------------------------------------

export const INTENTS = {
  // Basic navigation (from Prompt 17)
  NAVIGATE_HOME: "navigate_home",
  NAVIGATE_WEATHER: "navigate_weather",
  NAVIGATE_DISEASE: "navigate_disease",
  NAVIGATE_APMC: "navigate_apmc",
  SHOW_HELP: "show_help",

  // Advanced queries (Prompt 18)
  QUERY_CROP_PRICE: "query_crop_price",
  QUERY_WEATHER_TIME: "query_weather_time",
  QUERY_DISEASE_TREATMENT: "query_disease_treatment",
  COMPARE_PRICES: "compare_prices",
  READ_ALERTS: "read_alerts",
  BEST_APMC: "best_apmc",

  UNKNOWN: "unknown",
};

// ---------------------------------------------------------------------------
// Action Types
// ---------------------------------------------------------------------------

export const ACTIONS = {
  NAVIGATE: "navigate",
  SPEAK: "speak",
  SHOW_HELP: "show_help",
  CONFIRM: "confirm",
  NONE: "none",
};

// ---------------------------------------------------------------------------
// Basic Intent Keyword Patterns (one-shot commands)
// ---------------------------------------------------------------------------

const BASIC_INTENT_PATTERNS = {
  [INTENTS.NAVIGATE_WEATHER]: {
    [LANGUAGES.EN]: [
      "weather", "forecast", "temperature", "rain", "climate", "show weather",
    ],
    [LANGUAGES.HI]: [
      "मौसम", "मौसम बताओ", "बारिश", "तापमान", "मौसम दिखाओ",
    ],
    route: ROUTES.WEATHER,
  },
  [INTENTS.NAVIGATE_DISEASE]: {
    [LANGUAGES.EN]: [
      "disease", "detect disease", "crop disease", "plant disease", "scan", "diagnose",
    ],
    [LANGUAGES.HI]: [
      "रोग", "रोग पहचानो", "बीमारी", "फसल रोग", "रोग बताओ",
    ],
    route: ROUTES.DISEASE_DETECTION,
  },
  [INTENTS.NAVIGATE_APMC]: {
    [LANGUAGES.EN]: [
      "apmc", "mandi", "prices", "show prices", "market", "market price", "crop price",
    ],
    [LANGUAGES.HI]: [
      "भाव", "भाव बताओ", "मंडी", "मंडी भाव", "बाजार भाव", "दाम", "APMC",
    ],
    route: ROUTES.APMC,
  },
  [INTENTS.NAVIGATE_HOME]: {
    [LANGUAGES.EN]: ["home", "go home", "main page", "start"],
    [LANGUAGES.HI]: ["होम", "घर", "मुख्य पेज", "शुरू"],
    route: ROUTES.HOME,
  },
  [INTENTS.SHOW_HELP]: {
    [LANGUAGES.EN]: ["help", "commands", "what can you do", "voice commands"],
    [LANGUAGES.HI]: ["मदद", "मदद चाहिए", "सहायता", "कमांड"],
    route: null,
  },
};

// ---------------------------------------------------------------------------
// Advanced Intent Keyword Patterns (parameterized queries)
// ---------------------------------------------------------------------------

const ADVANCED_INTENT_PATTERNS = {
  [INTENTS.QUERY_CROP_PRICE]: {
    [LANGUAGES.EN]: [
      "price of", "prices of", "show .* prices", "how much is",
      ".* price in", "cost of", "rate of",
    ],
    [LANGUAGES.HI]: [
      "का भाव", "का दाम", "की कीमत", "भाव बताओ", "भाव दिखाओ",
    ],
    route: ROUTES.APMC,
  },
  [INTENTS.QUERY_WEATHER_TIME]: {
    [LANGUAGES.EN]: [
      "weather tomorrow", "weather today", "weather next week",
      "forecast for", "temperature tomorrow", "rain tomorrow",
      "will it rain", "weather this week",
    ],
    [LANGUAGES.HI]: [
      "कल का मौसम", "आज का मौसम", "कल बारिश", "अगले हफ्ते का मौसम",
      "कल तापमान",
    ],
    route: ROUTES.WEATHER,
  },
  [INTENTS.QUERY_DISEASE_TREATMENT]: {
    [LANGUAGES.EN]: [
      "how to treat", "treatment for", "cure for", "remedy for",
      "how to fix", "solution for", "what is .* disease",
    ],
    [LANGUAGES.HI]: [
      "का इलाज", "कैसे ठीक करें", "का उपचार", "का उपाय",
      "रोग का इलाज",
    ],
    route: ROUTES.DISEASE_DETECTION,
  },
  [INTENTS.COMPARE_PRICES]: {
    [LANGUAGES.EN]: [
      "compare prices", "price comparison", "compare .* and",
      "which apmc", "which mandi", "difference in price",
    ],
    [LANGUAGES.HI]: [
      "भाव तुलना", "कीमत तुलना", "मंडी तुलना", "किस मंडी में", "किस APMC में",
    ],
    route: ROUTES.APMC,
  },
  [INTENTS.READ_ALERTS]: {
    [LANGUAGES.EN]: [
      "read alerts", "weather alerts", "any alerts", "show alerts",
      "warnings", "read warnings",
    ],
    [LANGUAGES.HI]: [
      "अलर्ट पढ़ो", "चेतावनी", "अलर्ट बताओ", "चेतावनी बताओ",
    ],
    route: ROUTES.WEATHER,
  },
  [INTENTS.BEST_APMC]: {
    [LANGUAGES.EN]: [
      "best apmc", "best mandi", "best market", "highest price", "best price",
      "where to sell", "best place to sell",
    ],
    [LANGUAGES.HI]: [
      "सबसे अच्छी मंडी", "सबसे ज्यादा भाव", "कहाँ बेचें",
      "बेहतरीन मंडी", "सबसे अच्छा APMC",
    ],
    route: ROUTES.APMC,
  },
};

// ---------------------------------------------------------------------------
// Voice Response Texts
// ---------------------------------------------------------------------------

const RESPONSES = {
  [INTENTS.NAVIGATE_WEATHER]: {
    [LANGUAGES.EN]: "Opening weather forecast.",
    [LANGUAGES.HI]: "मौसम की जानकारी दिखा रहे हैं।",
  },
  [INTENTS.NAVIGATE_DISEASE]: {
    [LANGUAGES.EN]: "Opening disease detection.",
    [LANGUAGES.HI]: "रोग पहचान खोल रहे हैं।",
  },
  [INTENTS.NAVIGATE_APMC]: {
    [LANGUAGES.EN]: "Opening APMC prices.",
    [LANGUAGES.HI]: "APMC भाव दिखा रहे हैं।",
  },
  [INTENTS.NAVIGATE_HOME]: {
    [LANGUAGES.EN]: "Going to home page.",
    [LANGUAGES.HI]: "मुख्य पेज पर जा रहे हैं।",
  },
  [INTENTS.SHOW_HELP]: {
    [LANGUAGES.EN]: "Here are the available commands.",
    [LANGUAGES.HI]: "यहाँ उपलब्ध कमांड हैं।",
  },
  [INTENTS.QUERY_CROP_PRICE]: {
    [LANGUAGES.EN]: "Opening APMC prices. You can search for {crop} there.",
    [LANGUAGES.HI]: "APMC भाव खोल रहे हैं। वहाँ {crop} खोजें।",
  },
  [INTENTS.QUERY_WEATHER_TIME]: {
    [LANGUAGES.EN]: "Opening weather forecast. Check {time} forecast.",
    [LANGUAGES.HI]: "मौसम की जानकारी दिखा रहे हैं। {time} का पूर्वानुमान देखें।",
  },
  [INTENTS.QUERY_DISEASE_TREATMENT]: {
    [LANGUAGES.EN]: "Opening disease detection. You can look up {disease} treatment there.",
    [LANGUAGES.HI]: "रोग पहचान खोल रहे हैं। वहाँ {disease} का इलाज देखें।",
  },
  [INTENTS.COMPARE_PRICES]: {
    [LANGUAGES.EN]: "Opening APMC prices for comparison.",
    [LANGUAGES.HI]: "तुलना के लिए APMC भाव खोल रहे हैं।",
  },
  [INTENTS.READ_ALERTS]: {
    [LANGUAGES.EN]: "Opening weather alerts.",
    [LANGUAGES.HI]: "मौसम अलर्ट दिखा रहे हैं।",
  },
  [INTENTS.BEST_APMC]: {
    [LANGUAGES.EN]: "Opening APMC prices to find the best market.",
    [LANGUAGES.HI]: "सबसे अच्छा APMC खोजने के लिए भाव दिखा रहे हैं।",
  },
  [INTENTS.UNKNOWN]: {
    [LANGUAGES.EN]: "Sorry, I did not understand that command.",
    [LANGUAGES.HI]: "क्षमा करें, यह कमांड समझ नहीं आई।",
  },
};

// ---------------------------------------------------------------------------
// Conversation Follow-up Responses
// ---------------------------------------------------------------------------

const FOLLOW_UP_RESPONSES = {
  askLocation: {
    [LANGUAGES.EN]: "For which location?",
    [LANGUAGES.HI]: "किस जगह के लिए?",
  },
  askCrop: {
    [LANGUAGES.EN]: "Which crop are you looking for?",
    [LANGUAGES.HI]: "कौन सी फसल?",
  },
  confirmAction: {
    [LANGUAGES.EN]: "Do you want me to proceed? Say yes or no.",
    [LANGUAGES.HI]: "क्या आगे बढ़ूँ? हाँ या नहीं बोलें।",
  },
  confirmed: {
    [LANGUAGES.EN]: "Done.",
    [LANGUAGES.HI]: "हो गया।",
  },
  cancelled: {
    [LANGUAGES.EN]: "Cancelled.",
    [LANGUAGES.HI]: "रद्द कर दिया।",
  },
  greeting: {
    [LANGUAGES.EN]: "Hello! How can I help you? Say 'help' to see available commands.",
    [LANGUAGES.HI]: "नमस्ते! मैं कैसे मदद कर सकता हूँ? 'मदद' बोलें उपलब्ध कमांड देखने के लिए।",
  },
};

// ---------------------------------------------------------------------------
// Available Commands (for help display - basic + advanced)
// ---------------------------------------------------------------------------

export const AVAILABLE_COMMANDS = [
  {
    intent: INTENTS.NAVIGATE_WEATHER,
    label: { [LANGUAGES.EN]: "Weather Forecast", [LANGUAGES.HI]: "मौसम की जानकारी" },
    examples: {
      [LANGUAGES.EN]: ["weather", "show weather", "forecast"],
      [LANGUAGES.HI]: ["मौसम बताओ", "मौसम दिखाओ"],
    },
    offline: true,
  },
  {
    intent: INTENTS.NAVIGATE_DISEASE,
    label: { [LANGUAGES.EN]: "Disease Detection", [LANGUAGES.HI]: "रोग पहचान" },
    examples: {
      [LANGUAGES.EN]: ["detect disease", "scan crop", "diagnose"],
      [LANGUAGES.HI]: ["रोग पहचानो", "रोग बताओ"],
    },
    offline: true,
  },
  {
    intent: INTENTS.NAVIGATE_APMC,
    label: { [LANGUAGES.EN]: "APMC Price", [LANGUAGES.HI]: "APMC भाव" },
    examples: {
      [LANGUAGES.EN]: ["show prices", "apmc prices", "market price"],
      [LANGUAGES.HI]: ["भाव बताओ", "APMC भाव"],
    },
    offline: true,
  },
  {
    intent: INTENTS.NAVIGATE_HOME,
    label: { [LANGUAGES.EN]: "Home Page", [LANGUAGES.HI]: "मुख्य पेज" },
    examples: {
      [LANGUAGES.EN]: ["home", "go home"],
      [LANGUAGES.HI]: ["होम", "घर"],
    },
    offline: true,
  },
  {
    intent: INTENTS.SHOW_HELP,
    label: { [LANGUAGES.EN]: "Help", [LANGUAGES.HI]: "सहायता" },
    examples: {
      [LANGUAGES.EN]: ["help", "commands"],
      [LANGUAGES.HI]: ["मदद", "सहायता"],
    },
    offline: true,
  },
];

export const ADVANCED_COMMANDS = [
  {
    intent: INTENTS.QUERY_CROP_PRICE,
    label: { [LANGUAGES.EN]: "Crop Prices", [LANGUAGES.HI]: "फसल भाव" },
    examples: {
      [LANGUAGES.EN]: ["show wheat prices", "price of rice in Punjab"],
      [LANGUAGES.HI]: ["गेहूं का भाव", "पंजाब में चावल का दाम"],
    },
    offline: true,
  },
  {
    intent: INTENTS.QUERY_WEATHER_TIME,
    label: { [LANGUAGES.EN]: "Weather by Time", [LANGUAGES.HI]: "समय अनुसार मौसम" },
    examples: {
      [LANGUAGES.EN]: ["weather tomorrow", "will it rain today"],
      [LANGUAGES.HI]: ["कल का मौसम", "आज बारिश होगी"],
    },
    offline: true,
  },
  {
    intent: INTENTS.QUERY_DISEASE_TREATMENT,
    label: { [LANGUAGES.EN]: "Disease Treatment", [LANGUAGES.HI]: "रोग उपचार" },
    examples: {
      [LANGUAGES.EN]: ["how to treat paddy blast", "cure for leaf blight"],
      [LANGUAGES.HI]: ["धान ब्लास्ट का इलाज", "पत्ती झुलसा का उपचार"],
    },
    offline: true,
  },
  {
    intent: INTENTS.COMPARE_PRICES,
    label: { [LANGUAGES.EN]: "Compare Prices", [LANGUAGES.HI]: "भाव तुलना" },
    examples: {
      [LANGUAGES.EN]: ["compare prices in Ludhiana and Amritsar"],
      [LANGUAGES.HI]: ["लुधियाना और अमृतसर में भाव तुलना"],
    },
    offline: true,
  },
  {
    intent: INTENTS.READ_ALERTS,
    label: { [LANGUAGES.EN]: "Weather Alerts", [LANGUAGES.HI]: "मौसम अलर्ट" },
    examples: {
      [LANGUAGES.EN]: ["read alerts", "any warnings"],
      [LANGUAGES.HI]: ["अलर्ट पढ़ो", "चेतावनी बताओ"],
    },
    offline: true,
  },
  {
    intent: INTENTS.BEST_APMC,
    label: { [LANGUAGES.EN]: "Best APMC", [LANGUAGES.HI]: "सबसे अच्छा APMC" },
    examples: {
      [LANGUAGES.EN]: ["best apmc", "where to sell"],
      [LANGUAGES.HI]: ["सबसे अच्छा APMC", "कहाँ बेचें"],
    },
    offline: true,
  },
];

// ---------------------------------------------------------------------------
// Entity Data - Locations
// ---------------------------------------------------------------------------

const INDIAN_STATES = [
  "Punjab", "Haryana", "Uttar Pradesh", "Madhya Pradesh", "Rajasthan",
  "Maharashtra", "Gujarat", "Karnataka", "Tamil Nadu", "Andhra Pradesh",
  "Telangana", "Bihar", "West Bengal", "Odisha", "Chhattisgarh",
  "Jharkhand", "Assam", "Kerala", "Himachal Pradesh", "Uttarakhand",
];

const INDIAN_STATES_HI = [
  "पंजाब", "हरियाणा", "उत्तर प्रदेश", "मध्य प्रदेश", "राजस्थान",
  "महाराष्ट्र", "गुजरात", "कर्नाटक", "तमिलनाडु", "आंध्र प्रदेश",
  "तेलंगाना", "बिहार", "पश्चिम बंगाल", "ओडिशा", "छत्तीसगढ़",
  "झारखंड", "असम", "केरल", "हिमाचल प्रदेश", "उत्तराखंड",
];

const MANDI_CITIES = [
  "Ludhiana", "Amritsar", "Jalandhar", "Chandigarh", "Karnal", "Hisar",
  "Lucknow", "Kanpur", "Agra", "Varanasi", "Jaipur", "Jodhpur", "Kota",
  "Indore", "Bhopal", "Nagpur", "Pune", "Mumbai", "Nashik",
  "Ahmedabad", "Surat", "Rajkot", "Bengaluru", "Hyderabad", "Chennai",
  "Kolkata", "Patna", "Bhubaneswar", "Raipur", "Ranchi", "Guwahati",
  "Dehradun", "Shimla", "Thiruvananthapuram",
];

const MANDI_CITIES_HI = [
  "लुधियाना", "अमृतसर", "जालंधर", "चंडीगढ़", "करनाल", "हिसार",
  "लखनऊ", "कानपुर", "आगरा", "वाराणसी", "जयपुर", "जोधपुर", "कोटा",
  "इंदौर", "भोपाल", "नागपुर", "पुणे", "मुंबई", "नासिक",
  "अहमदाबाद", "सूरत", "राजकोट", "बेंगलुरु", "हैदराबाद", "चेन्नई",
  "कोलकाता", "पटना", "भुवनेश्वर", "रायपुर", "रांची", "गुवाहाटी",
  "देहरादून", "शिमला", "तिरुवनंतपुरम",
];

// ---------------------------------------------------------------------------
// Entity Data - Diseases
// ---------------------------------------------------------------------------

const CROP_DISEASES_EN = [
  "paddy blast", "rice blast", "leaf blight", "bacterial leaf blight",
  "brown spot", "sheath blight", "stem rot", "root rot",
  "rust", "wheat rust", "yellow rust", "black rust",
  "powdery mildew", "downy mildew",
  "late blight", "early blight",
  "wilt", "fusarium wilt",
  "anthracnose", "smut", "mosaic virus", "leaf curl",
  "tikka disease", "blast", "blight",
];

const CROP_DISEASES_HI = [
  "धान ब्लास्ट", "पत्ती झुलसा", "भूरा धब्बा", "तना सड़न",
  "जड़ सड़न", "गेरुई", "चूर्णिल आसिता", "मृदुरोमिल आसिता",
  "उकठा", "कंडुआ", "मोजेक", "पत्ती मोड़",
  "ब्लास्ट", "झुलसा",
];

// ---------------------------------------------------------------------------
// Entity Data - Time References
// ---------------------------------------------------------------------------

const TIME_REFERENCES_EN = {
  today: "today",
  tomorrow: "tomorrow",
  yesterday: "yesterday",
  "day after tomorrow": "day after tomorrow",
  "next week": "next week",
  "this week": "this week",
};

const TIME_REFERENCES_HI = {
  "आज": "today",
  "कल": "tomorrow",
  "परसों": "day after tomorrow",
  "अगले हफ्ते": "next week",
  "इस हफ्ते": "this week",
};

// ---------------------------------------------------------------------------
// Entity Data - Crops (derived from constants)
// ---------------------------------------------------------------------------

const CROPS_EN = SUPPORTED_CROPS.map((c) => c.toLowerCase());

const CROPS_HI_MAP = {
  "धान": "Paddy",
  "चावल": "Paddy",
  "गेहूं": "Wheat",
  "कपास": "Cotton",
  "गन्ना": "Sugarcane",
  "टमाटर": "Tomato",
  "आलू": "Potato",
  "प्याज": "Onion",
  "मिर्च": "Chilli",
  "मक्का": "Maize",
  "दालें": "Pulses",
  "दाल": "Pulses",
  "तिलहन": "Oilseeds",
  "बाजरा": "Millets",
  "ज्वार": "Millets",
  "रागी": "Millets",
};

// ---------------------------------------------------------------------------
// Confirmation Keywords
// ---------------------------------------------------------------------------

const CONFIRM_KEYWORDS = {
  yes: ["yes", "yeah", "yep", "sure", "ok", "okay", "confirm", "proceed", "go ahead"],
  no: ["no", "nope", "cancel", "stop", "nevermind", "never mind"],
  yesHi: ["हाँ", "हां", "जी", "ठीक", "ठीक है", "चलो", "आगे बढ़ो"],
  noHi: ["नहीं", "मत", "रुको", "बंद करो", "रद्द"],
};

// ---------------------------------------------------------------------------
// Entity Extraction Functions
// ---------------------------------------------------------------------------

/**
 * Extract crop names from text.
 *
 * @param {string} text - Normalized input text.
 * @returns {string[]} Matched crop names (canonical English form).
 */
export function extractCrops(text) {
  const lower = text.toLowerCase();
  const found = [];

  for (const crop of CROPS_EN) {
    if (lower.includes(crop)) {
      const canonical = SUPPORTED_CROPS.find((c) => c.toLowerCase() === crop);
      if (canonical && !found.includes(canonical)) {
        found.push(canonical);
      }
    }
  }

  for (const [hindi, english] of Object.entries(CROPS_HI_MAP)) {
    if (text.includes(hindi) && !found.includes(english)) {
      found.push(english);
    }
  }

  return found;
}

/**
 * Extract location names from text.
 *
 * @param {string} text - Input text.
 * @returns {string[]} Matched location names.
 */
export function extractLocations(text) {
  const lower = text.toLowerCase();
  const found = [];

  const allLocationsEn = [...INDIAN_STATES, ...MANDI_CITIES];
  for (const loc of allLocationsEn) {
    if (lower.includes(loc.toLowerCase()) && !found.includes(loc)) {
      found.push(loc);
    }
  }

  const allLocationsHi = [...INDIAN_STATES_HI, ...MANDI_CITIES_HI];
  for (let i = 0; i < allLocationsHi.length; i++) {
    if (text.includes(allLocationsHi[i])) {
      const enEquiv = i < INDIAN_STATES_HI.length
        ? INDIAN_STATES[i]
        : MANDI_CITIES[i - INDIAN_STATES_HI.length];
      if (enEquiv && !found.includes(enEquiv)) {
        found.push(enEquiv);
      }
    }
  }

  return found;
}

/**
 * Extract time references from text.
 *
 * @param {string} text - Input text.
 * @returns {string|null} Normalized time reference or null.
 */
export function extractTimeReference(text) {
  const lower = text.toLowerCase();

  for (const [phrase, normalized] of Object.entries(TIME_REFERENCES_EN)) {
    if (lower.includes(phrase)) {
      return normalized;
    }
  }

  for (const [phrase, normalized] of Object.entries(TIME_REFERENCES_HI)) {
    if (text.includes(phrase)) {
      return normalized;
    }
  }

  return null;
}

/**
 * Extract disease names from text.
 *
 * @param {string} text - Input text.
 * @returns {string[]} Matched disease names.
 */
export function extractDiseases(text) {
  const lower = text.toLowerCase();
  const found = [];

  for (const disease of CROP_DISEASES_EN) {
    if (lower.includes(disease) && !found.includes(disease)) {
      found.push(disease);
    }
  }

  for (const disease of CROP_DISEASES_HI) {
    if (text.includes(disease) && !found.includes(disease)) {
      found.push(disease);
    }
  }

  return found;
}

/**
 * Extract all entities from text.
 *
 * @param {string} text - Input text.
 * @returns {{ crops: string[], locations: string[], timeRef: string|null, diseases: string[] }}
 */
export function extractEntities(text) {
  if (!text || typeof text !== "string") {
    return { crops: [], locations: [], timeRef: null, diseases: [] };
  }
  return {
    crops: extractCrops(text),
    locations: extractLocations(text),
    timeRef: extractTimeReference(text),
    diseases: extractDiseases(text),
  };
}

// ---------------------------------------------------------------------------
// Intent Recognition Helpers
// ---------------------------------------------------------------------------

const CONFIDENCE_THRESHOLD = 0.5;

/**
 * Calculate match score between user input and a keyword.
 *
 * @param {string} input   - Normalized user input.
 * @param {string} keyword - Normalized keyword to match against.
 * @returns {number} Match confidence from 0 to 1.
 */
function calculateMatchScore(input, keyword) {
  const normalizedInput = input.toLowerCase().trim();
  const normalizedKeyword = keyword.toLowerCase().trim();

  if (!normalizedInput || !normalizedKeyword) {
    return 0;
  }

  if (normalizedInput === normalizedKeyword) {
    return 1.0;
  }

  if (normalizedInput.includes(normalizedKeyword)) {
    return 0.9;
  }

  if (normalizedKeyword.includes(normalizedInput)) {
    return 0.7;
  }

  const inputWords = normalizedInput.split(/\s+/);
  const keywordWords = normalizedKeyword.split(/\s+/);
  const matchCount = inputWords.filter((word) =>
    keywordWords.some((kw) => kw.includes(word) || word.includes(kw)),
  ).length;

  if (matchCount > 0) {
    const maxLen = Math.max(inputWords.length, keywordWords.length);
    return (matchCount / maxLen) * 0.8;
  }

  return 0;
}

/**
 * Try to match a regex-style pattern against input text.
 * Patterns may contain .* for wildcards.
 *
 * @param {string} input   - User input.
 * @param {string} pattern - Pattern (may contain .*).
 * @returns {number} Match confidence from 0 to 1.
 */
function calculateAdvancedMatchScore(input, pattern) {
  const normalizedInput = input.toLowerCase().trim();

  if (pattern.includes(".*")) {
    try {
      const regex = new RegExp(pattern.toLowerCase(), "i");
      if (regex.test(normalizedInput)) {
        return 0.85;
      }
    } catch {
      // Fallback to simple match if regex is invalid
    }
  }

  return calculateMatchScore(input, pattern);
}

// ---------------------------------------------------------------------------
// Basic Command Parsing (one-shot, used by VoiceButton)
// ---------------------------------------------------------------------------

/**
 * Parse a voice transcript for basic navigation commands.
 * This is the simple, stateless parser for one-shot commands.
 *
 * @param {string} text     - The voice transcript text.
 * @param {string} language - Current UI language.
 * @returns {{ intent: string, confidence: number, route: string|null, response: string }}
 */
export function parseCommand(text, language = LANGUAGES.EN) {
  if (!text || typeof text !== "string") {
    return {
      intent: INTENTS.UNKNOWN,
      confidence: 0,
      route: null,
      response: getResponse(INTENTS.UNKNOWN, language),
    };
  }

  const normalizedText = text.toLowerCase().trim();
  let bestMatch = { intent: INTENTS.UNKNOWN, confidence: 0, route: null };

  // Check basic patterns
  for (const [intent, config] of Object.entries(BASIC_INTENT_PATTERNS)) {
    for (const lang of [LANGUAGES.EN, LANGUAGES.HI]) {
      const keywords = config[lang] || [];
      for (const keyword of keywords) {
        const score = calculateMatchScore(normalizedText, keyword);
        if (score > bestMatch.confidence) {
          bestMatch = { intent, confidence: score, route: config.route };
        }
      }
    }
  }

  // Check advanced patterns if basic didn't match well
  if (bestMatch.confidence < 0.8) {
    for (const [intent, config] of Object.entries(ADVANCED_INTENT_PATTERNS)) {
      for (const lang of [LANGUAGES.EN, LANGUAGES.HI]) {
        const patterns = config[lang] || [];
        for (const pattern of patterns) {
          const score = calculateAdvancedMatchScore(normalizedText, pattern);
          if (score > bestMatch.confidence) {
            bestMatch = { intent, confidence: score, route: config.route };
          }
        }
      }
    }
  }

  if (bestMatch.confidence < CONFIDENCE_THRESHOLD) {
    bestMatch = { intent: INTENTS.UNKNOWN, confidence: bestMatch.confidence, route: null };
  }

  const entities = extractEntities(text);
  const response = buildResponse(bestMatch.intent, language, entities);

  return {
    intent: bestMatch.intent,
    confidence: bestMatch.confidence,
    route: bestMatch.route,
    response,
    entities,
  };
}

// ---------------------------------------------------------------------------
// Response Builder
// ---------------------------------------------------------------------------

/**
 * Get the raw response template for an intent.
 */
function getResponse(intent, language) {
  const templates = RESPONSES[intent];
  if (!templates) {
    return RESPONSES[INTENTS.UNKNOWN][language] || RESPONSES[INTENTS.UNKNOWN][LANGUAGES.EN];
  }
  return templates[language] || templates[LANGUAGES.EN];
}

/**
 * Build a response string, substituting extracted entity placeholders.
 */
function buildResponse(intent, language, entities) {
  let response = getResponse(intent, language);

  if (entities) {
    const crop = entities.crops.length > 0 ? entities.crops[0] : "";
    const location = entities.locations.length > 0 ? entities.locations[0] : "";
    const time = entities.timeRef || "";
    const disease = entities.diseases.length > 0 ? entities.diseases[0] : "";

    response = response
      .replace("{crop}", crop || (language === LANGUAGES.HI ? "फसल" : "the crop"))
      .replace("{location}", location || "")
      .replace("{time}", time || (language === LANGUAGES.HI ? "" : "the"))
      .replace("{disease}", disease || (language === LANGUAGES.HI ? "रोग" : "the disease"));
  }

  return response;
}

// ---------------------------------------------------------------------------
// Conversation Engine (multi-turn, context-aware)
// ---------------------------------------------------------------------------

const CONVERSATION_STATES = {
  IDLE: "idle",
  AWAITING_LOCATION: "awaiting_location",
  AWAITING_CROP: "awaiting_crop",
  AWAITING_CONFIRMATION: "awaiting_confirmation",
};

let messageIdCounter = 0;

function generateMessageId() {
  messageIdCounter += 1;
  return `msg_${Date.now()}_${messageIdCounter}`;
}

/**
 * ConversationEngine - Stateful, context-aware command processor.
 *
 * Maintains conversation history, accumulated entities,
 * and supports multi-turn slot-filling dialogues.
 */
export class ConversationEngine {
  /**
   * @param {string} language - Initial language preference.
   */
  constructor(language = LANGUAGES.EN) {
    this.messages = [];
    this.context = {
      crop: null,
      location: null,
      timeRef: null,
      disease: null,
      lastIntent: null,
    };
    this.conversationState = CONVERSATION_STATES.IDLE;
    this.pendingAction = null;
    this.language = language;

    this._loadHistory();
  }

  /**
   * Process a user message and return a structured result.
   *
   * @param {string} text     - User input (voice transcript or typed text).
   * @param {string} language - Current UI language.
   * @returns {{ intent: string, confidence: number, route: string|null, response: string, action: string, entities: object }}
   */
  process(text, language = this.language) {
    this.language = language;

    if (!text || typeof text !== "string" || !text.trim()) {
      return this._buildResult(INTENTS.UNKNOWN, 0, null, ACTIONS.NONE, {});
    }

    const trimmed = text.trim();

    // Add user message to history
    const entities = extractEntities(trimmed);
    this._mergeEntities(entities);

    // Handle conversation state (slot-filling)
    if (this.conversationState !== CONVERSATION_STATES.IDLE) {
      return this._handleFollowUp(trimmed, entities, language);
    }

    // Check for confirmation keywords (standalone "yes"/"no")
    if (this._isConfirmation(trimmed)) {
      return this._handleConfirmation(trimmed, language);
    }

    // Parse intent
    const parsed = parseCommand(trimmed, language);

    // Store user message
    this._addMessage("user", trimmed, parsed.intent, entities, parsed.confidence);

    // Determine if we need more info (slot-filling)
    if (this._needsMoreInfo(parsed.intent, entities)) {
      return this._askForMoreInfo(parsed.intent, entities, language);
    }

    // Build response with entity context
    const response = buildResponse(parsed.intent, language, {
      crops: entities.crops.length > 0 ? entities.crops : (this.context.crop ? [this.context.crop] : []),
      locations: entities.locations.length > 0 ? entities.locations : (this.context.location ? [this.context.location] : []),
      timeRef: entities.timeRef || this.context.timeRef,
      diseases: entities.diseases.length > 0 ? entities.diseases : (this.context.disease ? [this.context.disease] : []),
    });

    // Store assistant response
    this._addMessage("assistant", response);

    // Update context
    this.context.lastIntent = parsed.intent;

    const action = parsed.intent === INTENTS.SHOW_HELP
      ? ACTIONS.SHOW_HELP
      : parsed.route
        ? ACTIONS.NAVIGATE
        : ACTIONS.SPEAK;

    this._saveHistory();

    return {
      intent: parsed.intent,
      confidence: parsed.confidence,
      route: parsed.route,
      response,
      action,
      entities: {
        crops: entities.crops,
        locations: entities.locations,
        timeRef: entities.timeRef,
        diseases: entities.diseases,
      },
    };
  }

  /**
   * Add an assistant-only message (e.g., greeting, error).
   */
  addAssistantMessage(text) {
    this._addMessage("assistant", text);
    this._saveHistory();
  }

  /**
   * Get all conversation messages.
   *
   * @returns {Array<{ id: string, role: string, text: string, timestamp: string, intent?: string, entities?: object, confidence?: number }>}
   */
  getMessages() {
    return [...this.messages];
  }

  /**
   * Get the current accumulated context.
   */
  getContext() {
    return { ...this.context };
  }

  /**
   * Clear the conversation context (keep messages).
   */
  clearContext() {
    this.context = {
      crop: null,
      location: null,
      timeRef: null,
      disease: null,
      lastIntent: null,
    };
    this.conversationState = CONVERSATION_STATES.IDLE;
    this.pendingAction = null;
  }

  /**
   * Clear all messages and reset context.
   */
  clear() {
    this.messages = [];
    this.clearContext();
    storage.remove(STORAGE_KEYS.VOICE_CHAT_HISTORY);
  }

  /**
   * Update the engine language.
   */
  setLanguage(language) {
    this.language = language;
  }

  // --- Private Methods -------------------------------------------------------

  _addMessage(role, text, intent = null, entities = null, confidence = null) {
    const message = {
      id: generateMessageId(),
      role,
      text,
      timestamp: new Date().toISOString(),
    };
    if (intent) message.intent = intent;
    if (entities) message.entities = entities;
    if (confidence !== null) message.confidence = confidence;

    this.messages.push(message);
  }

  _mergeEntities(entities) {
    if (entities.crops.length > 0) {
      this.context.crop = entities.crops[0];
    }
    if (entities.locations.length > 0) {
      this.context.location = entities.locations[0];
    }
    if (entities.timeRef) {
      this.context.timeRef = entities.timeRef;
    }
    if (entities.diseases.length > 0) {
      this.context.disease = entities.diseases[0];
    }
  }

  _needsMoreInfo(intent, entities) {
    if (intent === INTENTS.QUERY_CROP_PRICE && entities.crops.length === 0 && !this.context.crop) {
      return true;
    }
    if (intent === INTENTS.COMPARE_PRICES && entities.locations.length < 2 && !this.context.location) {
      return true;
    }
    return false;
  }

  _askForMoreInfo(intent, entities, language) {
    let followUp;
    if (intent === INTENTS.QUERY_CROP_PRICE && entities.crops.length === 0) {
      this.conversationState = CONVERSATION_STATES.AWAITING_CROP;
      followUp = FOLLOW_UP_RESPONSES.askCrop[language] || FOLLOW_UP_RESPONSES.askCrop[LANGUAGES.EN];
    } else if (intent === INTENTS.COMPARE_PRICES && entities.locations.length < 2) {
      this.conversationState = CONVERSATION_STATES.AWAITING_LOCATION;
      followUp = FOLLOW_UP_RESPONSES.askLocation[language] || FOLLOW_UP_RESPONSES.askLocation[LANGUAGES.EN];
    } else {
      followUp = FOLLOW_UP_RESPONSES.askCrop[language] || FOLLOW_UP_RESPONSES.askCrop[LANGUAGES.EN];
      this.conversationState = CONVERSATION_STATES.AWAITING_CROP;
    }

    this.pendingAction = { intent, entities };
    this._addMessage("assistant", followUp);
    this._saveHistory();

    return {
      intent,
      confidence: 0.6,
      route: null,
      response: followUp,
      action: ACTIONS.SPEAK,
      entities: { crops: entities.crops, locations: entities.locations, timeRef: entities.timeRef, diseases: entities.diseases },
    };
  }

  _handleFollowUp(text, entities, language) {
    this._addMessage("user", text, null, entities);

    const prevIntent = this.pendingAction ? this.pendingAction.intent : this.context.lastIntent;
    const route = prevIntent
      ? (ADVANCED_INTENT_PATTERNS[prevIntent]?.route || BASIC_INTENT_PATTERNS[prevIntent]?.route || null)
      : null;

    // Merge newly extracted entities
    const mergedEntities = {
      crops: entities.crops.length > 0 ? entities.crops : (this.context.crop ? [this.context.crop] : []),
      locations: entities.locations.length > 0 ? entities.locations : (this.context.location ? [this.context.location] : []),
      timeRef: entities.timeRef || this.context.timeRef,
      diseases: entities.diseases.length > 0 ? entities.diseases : (this.context.disease ? [this.context.disease] : []),
    };

    // If the user just gave a bare noun that could be a crop
    if (this.conversationState === CONVERSATION_STATES.AWAITING_CROP && entities.crops.length === 0) {
      const possibleCrop = this._tryMatchCrop(text);
      if (possibleCrop) {
        mergedEntities.crops = [possibleCrop];
        this.context.crop = possibleCrop;
      }
    }

    // If the user just gave a bare location
    if (this.conversationState === CONVERSATION_STATES.AWAITING_LOCATION && entities.locations.length === 0) {
      const possibleLoc = this._tryMatchLocation(text);
      if (possibleLoc) {
        mergedEntities.locations = [possibleLoc];
        this.context.location = possibleLoc;
      }
    }

    const response = buildResponse(prevIntent || INTENTS.UNKNOWN, language, mergedEntities);

    this._addMessage("assistant", response);
    this.context.lastIntent = prevIntent;
    this.conversationState = CONVERSATION_STATES.IDLE;
    this.pendingAction = null;
    this._saveHistory();

    return {
      intent: prevIntent || INTENTS.UNKNOWN,
      confidence: 0.75,
      route,
      response,
      action: route ? ACTIONS.NAVIGATE : ACTIONS.SPEAK,
      entities: mergedEntities,
    };
  }

  _isConfirmation(text) {
    const lower = text.toLowerCase().trim();
    const allYes = [...CONFIRM_KEYWORDS.yes, ...CONFIRM_KEYWORDS.yesHi];
    const allNo = [...CONFIRM_KEYWORDS.no, ...CONFIRM_KEYWORDS.noHi];
    return allYes.includes(lower) || allNo.includes(lower);
  }

  _handleConfirmation(text, language) {
    const lower = text.toLowerCase().trim();
    const isYes = [...CONFIRM_KEYWORDS.yes, ...CONFIRM_KEYWORDS.yesHi].includes(lower);

    this._addMessage("user", text);

    if (isYes && this.pendingAction) {
      const response = FOLLOW_UP_RESPONSES.confirmed[language] || FOLLOW_UP_RESPONSES.confirmed[LANGUAGES.EN];
      this._addMessage("assistant", response);
      const result = {
        intent: this.pendingAction.intent,
        confidence: 1.0,
        route: ADVANCED_INTENT_PATTERNS[this.pendingAction.intent]?.route
          || BASIC_INTENT_PATTERNS[this.pendingAction.intent]?.route
          || null,
        response,
        action: ACTIONS.NAVIGATE,
        entities: this.pendingAction.entities || {},
      };
      this.conversationState = CONVERSATION_STATES.IDLE;
      this.pendingAction = null;
      this._saveHistory();
      return result;
    }

    const response = FOLLOW_UP_RESPONSES.cancelled[language] || FOLLOW_UP_RESPONSES.cancelled[LANGUAGES.EN];
    this._addMessage("assistant", response);
    this.conversationState = CONVERSATION_STATES.IDLE;
    this.pendingAction = null;
    this._saveHistory();

    return {
      intent: INTENTS.UNKNOWN,
      confidence: 1.0,
      route: null,
      response,
      action: ACTIONS.NONE,
      entities: {},
    };
  }

  _tryMatchCrop(text) {
    const lower = text.toLowerCase().trim();
    for (const crop of SUPPORTED_CROPS) {
      if (lower.includes(crop.toLowerCase())) {
        return crop;
      }
    }
    for (const [hindi, english] of Object.entries(CROPS_HI_MAP)) {
      if (text.includes(hindi)) {
        return english;
      }
    }
    // Try fuzzy: if the whole input is a single word, check starts-with
    const singleWord = lower.replace(/\s+/g, "");
    for (const crop of SUPPORTED_CROPS) {
      if (crop.toLowerCase().startsWith(singleWord) && singleWord.length >= 3) {
        return crop;
      }
    }
    return null;
  }

  _tryMatchLocation(text) {
    const lower = text.toLowerCase().trim();
    for (const loc of [...INDIAN_STATES, ...MANDI_CITIES]) {
      if (lower.includes(loc.toLowerCase())) {
        return loc;
      }
    }
    for (let i = 0; i < INDIAN_STATES_HI.length; i++) {
      if (text.includes(INDIAN_STATES_HI[i])) {
        return INDIAN_STATES[i];
      }
    }
    for (let i = 0; i < MANDI_CITIES_HI.length; i++) {
      if (text.includes(MANDI_CITIES_HI[i])) {
        return MANDI_CITIES[i];
      }
    }
    return null;
  }

  _saveHistory() {
    try {
      const toSave = this.messages.slice(-100);
      storage.set(STORAGE_KEYS.VOICE_CHAT_HISTORY, toSave);
    } catch {
      // Storage write failure is non-critical
    }
  }

  _loadHistory() {
    try {
      const saved = storage.get(STORAGE_KEYS.VOICE_CHAT_HISTORY, []);
      if (Array.isArray(saved)) {
        this.messages = saved;
      }
    } catch {
      this.messages = [];
    }
  }
}

// ---------------------------------------------------------------------------
// Voice Settings Management
// ---------------------------------------------------------------------------

export const DEFAULT_VOICE_SETTINGS = {
  speechRate: 0.9,
  voiceGender: "female",
  language: LANGUAGES.EN,
  autoSpeak: true,
};

/**
 * Load voice settings from localStorage, merging with defaults.
 *
 * @returns {typeof DEFAULT_VOICE_SETTINGS}
 */
export function getVoiceSettings() {
  const saved = storage.get(STORAGE_KEYS.VOICE_SETTINGS, null);
  if (!saved || typeof saved !== "object") {
    return { ...DEFAULT_VOICE_SETTINGS };
  }
  return { ...DEFAULT_VOICE_SETTINGS, ...saved };
}

/**
 * Persist voice settings to localStorage.
 *
 * @param {Partial<typeof DEFAULT_VOICE_SETTINGS>} settings
 */
export function saveVoiceSettings(settings) {
  const current = getVoiceSettings();
  const merged = { ...current, ...settings };
  storage.set(STORAGE_KEYS.VOICE_SETTINGS, merged);
  return merged;
}

// ---------------------------------------------------------------------------
// Tutorial State
// ---------------------------------------------------------------------------

/**
 * Check whether the voice tutorial has been shown.
 */
export function isTutorialShown() {
  return storage.get(STORAGE_KEYS.VOICE_TUTORIAL_SHOWN, false) === true;
}

/**
 * Mark the voice tutorial as shown.
 */
export function markTutorialShown() {
  storage.set(STORAGE_KEYS.VOICE_TUTORIAL_SHOWN, true);
}

// ---------------------------------------------------------------------------
// Text-to-Speech
// ---------------------------------------------------------------------------

const VOICE_LANG_MAP = {
  [LANGUAGES.EN]: "en-IN",
  [LANGUAGES.HI]: "hi-IN",
};

let currentUtterance = null;

/**
 * Check if speech synthesis is supported.
 *
 * @returns {boolean}
 */
export function isSpeechSynthesisSupported() {
  return typeof window !== "undefined" && Boolean(window.speechSynthesis);
}

/**
 * Find a suitable voice for the given language and gender preference.
 *
 * @param {string} langCode - BCP-47 language code (e.g., "en-IN").
 * @param {string} gender   - Preferred gender: "male" or "female".
 * @returns {SpeechSynthesisVoice|null}
 */
function findVoice(langCode, gender) {
  if (!isSpeechSynthesisSupported()) return null;

  const voices = window.speechSynthesis.getVoices();
  if (!voices || voices.length === 0) return null;

  // Try exact language + gender match
  const genderKeyword = gender === "male" ? /male/i : /female/i;
  const exactMatch = voices.find(
    (v) => v.lang === langCode && genderKeyword.test(v.name),
  );
  if (exactMatch) return exactMatch;

  // Try exact language match (any gender)
  const langMatch = voices.find((v) => v.lang === langCode);
  if (langMatch) return langMatch;

  // Try language prefix match (e.g., "en" for "en-IN")
  const prefix = langCode.split("-")[0];
  const prefixMatch = voices.find((v) => v.lang.startsWith(prefix));
  return prefixMatch || null;
}

/**
 * Speak the given text using the Web Speech Synthesis API.
 *
 * @param {string} text       - Text to speak.
 * @param {string} language   - Language code (LANGUAGES.EN or LANGUAGES.HI).
 * @param {object} [settings] - Optional voice settings override.
 * @returns {Promise<void>} Resolves when speech ends.
 */
export function speak(text, language = LANGUAGES.EN, settings = null) {
  return new Promise((resolve, reject) => {
    if (!isSpeechSynthesisSupported()) {
      reject(new Error("Speech synthesis is not supported in this browser."));
      return;
    }

    const voiceSettings = settings || getVoiceSettings();

    cancelSpeech();

    const utterance = new SpeechSynthesisUtterance(text);
    utterance.lang = VOICE_LANG_MAP[language] || "en-IN";
    utterance.rate = voiceSettings.speechRate || 0.9;
    utterance.pitch = 1;
    utterance.volume = 1;

    const voice = findVoice(utterance.lang, voiceSettings.voiceGender);
    if (voice) {
      utterance.voice = voice;
    }

    utterance.onend = () => {
      currentUtterance = null;
      resolve();
    };

    utterance.onerror = (event) => {
      currentUtterance = null;
      if (event.error === "canceled") {
        resolve();
        return;
      }
      reject(new Error(`Speech synthesis error: ${event.error}`));
    };

    currentUtterance = utterance;
    window.speechSynthesis.speak(utterance);
  });
}

/**
 * Cancel any ongoing speech synthesis.
 */
export function cancelSpeech() {
  if (typeof window !== "undefined" && window.speechSynthesis) {
    window.speechSynthesis.cancel();
  }
  currentUtterance = null;
}

/**
 * Check if speech synthesis is currently speaking.
 *
 * @returns {boolean}
 */
export function isSpeaking() {
  return (
    typeof window !== "undefined" &&
    window.speechSynthesis &&
    window.speechSynthesis.speaking
  );
}

// ---------------------------------------------------------------------------
// Browser Compatibility
// ---------------------------------------------------------------------------

/**
 * Check browser compatibility for voice features.
 *
 * @returns {{ speechRecognition: boolean, speechSynthesis: boolean, microphone: boolean, isFullySupported: boolean }}
 */
export function checkCompatibility() {
  const hasSpeechRecognition =
    typeof window !== "undefined" &&
    Boolean(window.SpeechRecognition || window.webkitSpeechRecognition);

  const hasSpeechSynthesis =
    typeof window !== "undefined" && Boolean(window.speechSynthesis);

  const hasMicrophone =
    typeof navigator !== "undefined" &&
    Boolean(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);

  return {
    speechRecognition: hasSpeechRecognition,
    speechSynthesis: hasSpeechSynthesis,
    microphone: hasMicrophone,
    isFullySupported:
      hasSpeechRecognition && hasSpeechSynthesis && hasMicrophone,
  };
}

// ---------------------------------------------------------------------------
// Microphone Permission
// ---------------------------------------------------------------------------

/**
 * Request microphone permission from the user.
 *
 * @returns {Promise<"granted"|"denied">}
 */
export async function requestMicrophonePermission() {
  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    return "denied";
  }

  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    stream.getTracks().forEach((track) => track.stop());
    return "granted";
  } catch {
    return "denied";
  }
}

/**
 * Query the current microphone permission state without prompting.
 *
 * @returns {Promise<"granted"|"denied"|"prompt">}
 */
export async function getMicrophonePermissionState() {
  if (!navigator.permissions) {
    return "prompt";
  }

  try {
    const result = await navigator.permissions.query({ name: "microphone" });
    return result.state;
  } catch {
    return "prompt";
  }
}