File size: 51,823 Bytes
4c7bea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>PinScript V6 Digital Dictionary for TradingView</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"/>
  <style>
    body {
      font-family: 'Inter', sans-serif;
    }
    .code-block {
      background: #1e293b;
      color: #e2e8f0;
      padding: 1rem;
      border-radius: 0.5rem;
      font-family: 'Courier New', monospace;
      overflow-x: auto;
      border-left: 4px solid #3b82f6;
    }
    .highlight {
      background-color: #3b82f610;
      padding: 0.2rem 0.4rem;
      border-radius: 0.25rem;
      font-weight: 500;
    }
    .indicator-card:hover {
      transform: translateY(-4px);
      transition: all 0.3s ease;
    }
    .search-highlight {
      background-color: #fbbf24;
      color: #000;
      font-weight: 600;
      padding: 0.1rem 0.3rem;
      border-radius: 0.25rem;
    }
    .tooltip {
      position: relative;
      display: inline-block;
    }
    .tooltip .tooltiptext {
      visibility: hidden;
      width: 200px;
      background-color: #374151;
      color: #fff;
      text-align: center;
      border-radius: 6px;
      padding: 8px;
      position: absolute;
      z-index: 1;
      bottom: 125%;
      left: 50%;
      margin-left: -100px;
      opacity: 0;
      transition: opacity 0.3s;
      font-size: 14px;
      border: 1px solid #4b5563;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    .tooltip:hover .tooltiptext {
      visibility: visible;
      opacity: 1;
    }
    .sync-icon {
      transition: all 0.3s ease;
    }
    .sync-icon.syncing {
      animation: spin 1s linear infinite;
    }
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  </style>
</head>
<body class="bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 text-white min-h-screen">

  <!-- Header -->
  <header class="bg-black/30 backdrop-blur-md border-b border-white/10 sticky top-0 z-50">
    <div class="container mx-auto px-6 py-4">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-3">
          <div class="text-3xl"><i class="fab fa-trade-federation text-blue-400"></i></div>
          <div>
            <h1 class="text-2xl font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">PinScript V6 Dictionary</h1>
            <p class="text-sm text-gray-300">Digital Kamus Indikator TradingView</p>
          </div>
        </div>
        <div class="flex items-center space-x-6">
          <div class="hidden md:flex items-center space-x-4 text-sm text-gray-300">
            <span><i class="fas fa-database mr-1"></i> LocalStorage</span>
            <span><i class="fas fa-code mr-1"></i> PineScript V6</span>
            <span><i class="fas fa-chart-line mr-1"></i> Real-time Analysis</span>
          </div>
          <div class="tooltip">
            <button id="syncBtn" class="flex items-center space-x-2 bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg transition-colors">
              <i id="syncIcon" class="fas fa-sync-alt sync-icon"></i>
              <span>Sinkron</span>
            </button>
            <div class="tooltiptext">
              Sinkronisasi dengan database TradingView dan penyimpanan lokal. Memastikan Anda memiliki versi terbaru dari semua indikator.
            </div>
          </div>
          <div class="tooltip">
            <button id="addIndicatorBtn" class="flex items-center space-x-2 bg-green-600 hover:bg-green-700 px-4 py-2 rounded-lg transition-colors">
              <i class="fas fa-plus"></i>
              <span>Tambah</span>
            </button>
            <div class="tooltiptext">
              Tambahkan indikator PinScript V6 baru ke dalam kamus digital Anda. Bagikan dengan komunitas trader!
            </div>
          </div>
        </div>
      </div>
    </div>
  </header>

  <!-- Add Indicator Modal -->
  <div id="addIndicatorModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4">
    <div class="bg-slate-800 rounded-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto border border-white/10">
      <div class="p-6 border-b border-white/10">
        <div class="flex justify-between items-center">
          <h3 class="text-xl font-bold">Tambah Indikator Baru</h3>
          <button onclick="closeAddModal()" class="text-gray-400 hover:text-white">
            <i class="fas fa-times text-2xl"></i>
          </button>
        </div>
      </div>
      
      <form id="addIndicatorForm" class="p-6 space-y-6">
        <div>
          <label class="block text-sm font-medium mb-2">Nama Indikator <span class="text-red-400">*</span></label>
          <input type="text" id="indicatorTitle" required 
            class="w-full bg-white/10 border border-white/20 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 text-white placeholder-gray-300" 
            placeholder="Contoh: SuperTrend Advanced" />
        </div>
        
        <div>
          <label class="block text-sm font-medium mb-2">Kategori <span class="text-red-400">*</span></label>
          <select id="indicatorCategory" required class="w-full bg-white/10 border border-white/20 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 text-white">
            <option value="">Pilih kategori...</option>
            <option value="trend">Indikator Tren</option>
            <option value="oscillator">Oscillator</option>
            <option value="volume">Volume</option>
            <option value="volatility">Volatilitas</option>
            <option value="pattern">Pola & Strategi</option>
            <option value="custom">Custom Indikator</option>
          </select>
        </div>
        
        <div>
          <label class="block text-sm font-medium mb-2">Script PinScript V6 <span class="text-red-400">*</span></label>
          <div class="mb-2 text-xs text-gray-400">Mulai dengan //@version=6 untuk kompatibilitas</div>
          <textarea id="indicatorScript" required rows="8"
            class="w-full bg-white/10 border border-white/20 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 text-white placeholder-gray-300 font-mono"
            placeholder="//@version=6
indicator(&quot;Nama Indikator&quot;, overlay=true)

// Kode PythonScript Anda...
"></textarea>
        </div>
        
        <div>
          <label class="block text-sm font-medium mb-2">Penjelasan Indikator <span class="text-red-400">*</span></label>
          <textarea id="indicatorExplanation" required rows="3"
            class="w-full bg-white/10 border border-white/20 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 text-white placeholder-gray-300"
            placeholder="Jelaskan secara ringkas apa yang dilakukan indikator ini dan bagaimana cara kerjanya..."></textarea>
        </div>
        
        <div>
          <label class="block text-sm font-medium mb-2">Metode Penggunaan <span class="text-red-400">*</span></label>
          <textarea id="indicatorUsage" required rows="3"
            class="w-full bg-white/10 border border-white/20 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 text-white placeholder-gray-300"
            placeholder="Jelaskan strategi, parameter, dan kondisi yang ideal untuk menggunakan indikator ini..."></textarea>
        </div>
        
        <div>
          <label class="block text-sm font-medium mb-2">Tags (pisahkan dengan koma)</label>
          <input type="text" id="indicatorTags"
            class="w-full bg-white/10 border border-white/20 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 text-white placeholder-gray-300"
            placeholder="trend, breakout, volatility, advance..." />
        </div>
        
        <div class="flex items-center space-x-3">
          <input type="checkbox" id="shareWithCommunity" class="w-4 h-4" checked>
          <label for="shareWithCommunity" class="text-sm">Bagikan dengan komunitas untuk disetujui (dianjurkan)</label>
        </div>
        
        <div class="flex space-x-3 pt-4">
          <button type="button" onclick="closeAddModal()" class="flex-1 bg-white/10 hover:bg-white/20 text-white font-medium py-3 px-6 rounded-xl transition-colors">
            Batal
          </button>
          <button type="submit" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-6 rounded-xl transition-colors">
            Tambahkan ke Kamus
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- Sync Status Modal -->
  <div id="syncModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4">
    <div class="bg-slate-800 rounded-2xl max-w-md w-full border border-white/10">
      <div class="p-6">
        <div class="flex flex-col items-center text-center space-y-4">
          <div id="syncStatusIcon" class="text-6xl">
            <i class="fas fa-sync-alt sync-icon syncing"></i>
          </div>
          <h3 id="syncTitle" class="text-xl font-bold">Menyinkronkan Data</h3>
          <p id="syncMessage" class="text-gray-300">Menghubungkan dengan database TradingView dan memeriksa pembaruan...</p>
          <div id="syncProgressBar" class="w-full bg-white/10 rounded-full h-2">
            <div id="syncProgress" class="bg-blue-500 h-2 rounded-full" style="width: 20%"></div>
          </div>
          <div id="syncDetails" class="text-xs text-gray-400 mt-2 max-h-32 overflow-y-auto w-full"></div>
        </div>
      </div>
    </div>
  </div>

  <main class="container mx-auto px-6 py-8 flex flex-col lg:flex-row gap-8">

    <!-- Sidebar -->
    <aside class="lg:w-80 flex-shrink-0">
      <div class="bg-black/30 backdrop-blur-md rounded-2xl p-6 border border-white/10 sticky top-24">
        
        <!-- Search Input -->
        <div class="mb-6">
          <label class="block text-sm font-medium mb-2">🔍 Cari Indikator</label>
          <div class="relative">
            <input 
              type="text" 
              id="searchInput" 
              placeholder="Cari berdasarkan nama, fungsi, atau kata kunci..." 
              class="w-full bg-white/10 border border-white/20 rounded-xl px-4 py-3 pl-12 focus:outline-none focus:ring-2 focus:ring-blue-500 text-white placeholder-gray-300"
            />
            <i class="fas fa-search absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
          </div>
        </div>

        <!-- Category Filter -->
        <div class="mb-6">
          <label class="block text-sm font-medium mb-2">🔖 Kategori</label>
          <select id="categoryFilter" class="w-full bg-white/10 border border-white/20 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 text-white">
            <option value="">Semua Kategori</option>
            <option value="trend">Indikator Tren</option>
            <option value="oscillator">Oscillator</option>
            <option value="volume">Volume</option>
            <option value="volatility">Volatilitas</option>
            <option value="pattern">Pola & Strategi</option>
            <option value="custom">Custom Indikator</option>
          </select>
        </div>

        <!-- My Indicators -->
        <div class="mb-6">
          <div class="flex justify-between items-center mb-3">
            <label class="block text-sm font-medium">💾 Indikator Saya</label>
            <span id="myIndicatorsCount" class="text-xs bg-white/10 text-gray-300 px-2 py-1 rounded-full">0</span>
          </div>
          <div id="myIndicatorsList" class="space-y-2 max-h-32 overflow-y-auto">
            <p class="text-gray-400 text-sm">Tidak ada indikator pribadi</p>
          </div>
        </div>

        <!-- Favorite Indicators -->
        <div class="mb-6">
          <div class="flex justify-between items-center mb-3">
            <label class="block text-sm font-medium">⭐ Favorit Anda</label>
            <span id="favoritesCount" class="text-xs bg-white/10 text-gray-300 px-2 py-1 rounded-full">0</span>
          </div>
          <div id="favoritesList" class="space-y-2 max-h-32 overflow-y-auto">
            <p class="text-gray-400 text-sm">Belum ada favorit</p>
          </div>
        </div>

        <!-- Quick Stats -->
        <div class="bg-white/5 rounded-xl p-4 text-sm">
          <h4 class="font-semibold mb-2 flex items-center">
            <i class="fas fa-chart-bar mr-2"></i> Statistik
          </h4>
          <div class="space-y-1 text-gray-300">
            <div>Total Indikator: <span id="totalIndicators" class="float-right">24</span></div>
            <div>Terakhir disinkron: <span id="lastSync" class="float-right">Hari ini</span></div>
            <div>Database: <span class="float-right">Hybrid</span></div>
          </div>
        </div>

        <!-- Sync Status -->
        <div class="mt-6 p-3 bg-white/5 rounded-lg text-xs">
          <div class="flex items-center space-x-2 mb-2">
            <div id="connectionStatus" class="w-2 h-2 bg-green-500 rounded-full"></div>
            <span>Terhubung dengan server</span>
          </div>
          <div id="syncStatusDetails" class="text-gray-400">
            Sinkronisasi berhasil
          </div>
        </div>
      </div>
    </aside>

    <!-- Main Content -->
    <div class="flex-1">
      <div class="mb-6">
        <h2 class="text-2xl font-bold mb-2">📚 Kamus Digital PinScript V6</h2>
        <p class="text-gray-300">Kumpulan lengkap indikator, script, dan metode penggunaan PineScript v6 untuk <span class="highlight">TradingView</span>. <span id="cloudStatus" class="text-blue-400 text-sm"></span></p>
      </div>

      <!-- Instructions Banner -->
      <div class="bg-gradient-to-r from-blue-500/20 to-purple-500/20 border border-blue-500/30 rounded-xl p-4 mb-6">
        <div class="flex items-start space-x-3">
          <i class="fas fa-lightbulb text-yellow-400 mt-1"></i>
          <div>
            <h4 class="font-semibold text-yellow-400">Cara Menggunakan:</h4>
            <p class="text-sm text-gray-300">1. Gunakan kotak pencarian untuk menemukan indikator<br>2. Gunakan filter kategori untuk menyaring hasil<br>3. Klik tombol ❤️ untuk menandai favorit<br>4. Klik "Salin Script" untuk menyalin kode ke clipboard<br>5. Klik tombol "Tambah" untuk membuat indikator sendiri</p>
          </div>
        </div>
      </div>

      <!-- Cloud Sync Notification -->
      <div id="cloudNotification" class="hidden bg-green-500/20 border border-green-500/30 rounded-xl p-4 mb-6 items-center">
        <div class="flex items-center">
          <i class="fas fa-cloud text-green-400 mr-3"></i>
          <div>
            <h4 class="font-semibold text-green-400">Sinkronisasi Cloud</h4>
            <p class="text-sm text-green-300">Indikator baru telah diunggah ke cloud. Periksa indikator Anda di perangkat lain!</p>
          </div>
        </div>
      </div>

      <!-- Indicator List -->
      <div id="indicatorList" class="space-y-6">
        <!-- Indicators will be inserted here dynamically -->
      </div>
    </div>
  </main>

  <!-- Toast Notification -->
  <div id="toast" class="fixed bottom-6 right-6 bg-green-600 text-white px-6 py-3 rounded-xl shadow-lg hidden transition-all duration-300 transform opacity-0 translate-y-4">
    <div class="flex items-center">
      <i id="toastIcon" class="fas fa-check-circle mr-2"></i>
      <span id="toastMessage">Disalin ke clipboard!</span>
    </div>
  </div>

  <script>
    // Global variables
    let pinScriptDB = [];
    let customDB = [];
    let favorites = [];
    let myIndicators = [];
    let syncInProgress = false;
    
    // Configuration for cloud sync (mock endpoint)
    const CLOUD_CONFIG = {
      endpoint: 'https://example.com/api/pinescript',
      syncInterval: 300000, // 5 minutes
      maxRetries: 3
    };

    // DOM Elements
    const indicatorListEl = document.getElementById('indicatorList');
    const searchInputEl = document.getElementById('searchInput');
    const categoryFilterEl = document.getElementById('categoryFilter');
    const favoritesListEl = document.getElementById('favoritesList');
    const myIndicatorsListEl = document.getElementById('myIndicatorsList');
    const totalIndicatorsEl = document.getElementById('totalIndicators');
    const toastEl = document.getElementById('toast');
    const toastMessageEl = document.getElementById('toastMessage');
    const toastIconEl = document.getElementById('toastIcon');
    const syncBtn = document.getElementById('syncBtn');
    const syncIcon = document.getElementById('syncIcon');
    const addIndicatorBtn = document.getElementById('addIndicatorBtn');
    const addIndicatorModal = document.getElementById('addIndicatorModal');
    const syncModal = document.getElementById('syncModal');
    const syncTitle = document.getElementById('syncTitle');
    const syncMessage = document.getElementById('syncMessage');
    const syncProgress = document.getElementById('syncProgress');
    const syncDetails = document.getElementById('syncDetails');
    const connectionStatus = document.getElementById('connectionStatus');
    const syncStatusDetails = document.getElementById('syncStatusDetails');
    const cloudNotification = document.getElementById('cloudNotification');
    const lastSyncEl = document.getElementById('lastSync');
    const favoritesCountEl = document.getElementById('favoritesCount');
    const myIndicatorsCountEl = document.getElementById('myIndicatorsCount');
    const cloudStatusEl = document.getElementById('cloudStatus');

    // Initialize
    function init() {
      // Load data from localStorage
      loadDataFromStorage();
      
      // Initialize with demo data if empty
      if (pinScriptDB.length === 0) {
        initializeWithDemoData();
      }

      // Render everything
      renderIndicators(filterIndicators());
      renderFavorites();
      renderMyIndicators();
      updateStats();

      // Set up periodic sync
      setInterval(performSync, CLOUD_CONFIG.syncInterval);
      
      // Initial sync
      setTimeout(performSync, 2000);
    }

    // Load data from localStorage
    function loadDataFromStorage() {
      try {
        const storedMainDB = localStorage.getItem('pinescript_db_v6');
        const storedCustomDB = localStorage.getItem('pinescript_custom_db_v6');
        const storedFavorites = localStorage.getItem('pinescript_favorites_v6');
        const storedMyIndicators = localStorage.getItem('pinescript_my_indicators_v6');
        const lastSync = localStorage.getItem('pinescript_last_sync_v6');

        pinScriptDB = storedMainDB ? JSON.parse(storedMainDB) : [];
        customDB = storedCustomDB ? JSON.parse(storedCustomDB) : [];
        favorites = storedFavorites ? JSON.parse(storedFavorites) : [];
        myIndicators = storedMyIndicators ? JSON.parse(storedMyIndicators) : [];
        
        if (lastSync) {
          lastSyncEl.textContent = new Date(lastSync).toLocaleString('id-ID');
        } else {
          lastSyncEl.textContent = 'Belum pernah';
        }
      } catch (error) {
        console.error('Error loading data from storage:', error);
        showToast('Gagal memuat data dari penyimpanan lokal', true);
      }
    }

    // Save data to localStorage
    function saveDataToStorage() {
      try {
        localStorage.setItem('pinescript_db_v6', JSON.stringify(pinScriptDB));
        localStorage.setItem('pinescript_custom_db_v6', JSON.stringify(customDB));
        localStorage.setItem('pinescript_favorites_v6', JSON.stringify(favorites));
        localStorage.setItem('pinescript_my_indicators_v6', JSON.stringify(myIndicators));
        localStorage.setItem('pinescript_last_sync_v6', new Date().toISOString());
        
        lastSyncEl.textContent = new Date().toLocaleString('id-ID');
      } catch (error) {
        console.error('Error saving data to storage:', error);
        showToast('Gagal menyimpan data ke penyimpanan lokal', true);
        return false;
      }
      return true;
    }

    // Initialize with demo data
    function initializeWithDemoData() {
      pinScriptDB = [
        {
          id: 1,
          title: "Supertrend",
          category: "trend",
          script: `//@version=6
indicator("Supertrend", overlay=true, format=format.price, precision=2)

length = input.int(10, title="Length")
mult = input.float(3.0, title="Multiplier", step=0.1)
src = input.source(hlc3, title="Source")

atr = ta.sma(ta.tr, length)
up = src - mult * atr
dn = src + mult * atr

var trend = 1
var atr_up = up
var atr_dn = dn

trend := src[1] > atr_up[1] ? 1 : src[1] < atr_dn[1] ? -1 : trend[1]
atr_up := src <= atr_up[1] and src[1] >= atr_up[1] ? math.max(up, atr_up[1]) : up
atr_dn := src >= atr_dn[1] and src[1] <= atr_dn[1] ? math.min(dn, atr_dn[1]) : dn

trend_up = trend == 1 ? atr_up : na
trend_dn = trend == -1 ? atr_dn : na

plot(trend_up, color=color.green, title="Up Trend", linewidth=2)
plot(trend_dn, color=color.red, title="Down Trend", linewidth=2)

alertcondition(ta.crossover(close, trend_up), title="Buy Signal", message="Supertrend: Sinyal BELI!")
alertcondition(ta.crossunder(close, trend_dn), title="Sell Signal", message="Supertrend: Sinyal JUAL!")`,
          explanation: "Supertrend adalah indikator tren yang dinamis yang menunjukkan arah tren saat ini dengan garis di atas atau di bawah harga. Garis berubah warna berdasarkan perubahan tren, dengan dasar Average True Range (ATR) dan titik masuk/keluar berdasarkan volatilitas.",
          usage: "Gunakan Supertrend sebagai filter tren utama. Saat garis berada di bawah harga dan berwarna hijau, tren naik. Saat di atas harga dan merah, tren turun. Gunakan sinyal crossover untuk entry dan trailing stop untuk exit. Bisa digabung dengan RSI atau volume untuk konfirmasi.",
          tags: ["trend", "atr", "entry", "exit", "dynamic"],
          source: "builtin",
          createdAt: new Date().toISOString(),
          lastModified: new Date().toISOString()
        },
        {
          id: 2,
          title: "Relative Strength Index (RSI)",
          category: "oscillator",
          script: `//@version=6
indicator("RSI", shorttitle="RSI", format=format.price, precision=2)

rsiLength = input.int(14, title="Length")
overbought = input.int(70, title="Overbought Level")
oversold = input.int(30, title="Oversold Level")
src = input.source(close, title="Source")

vrsi = ta.rsi(src, rsiLength)

h0 = hline(overbought, "Overbought", color=color.red)
h1 = hline(oversold, "Oversold", color=color.green)
h2 = hline(50, "Midline", color=color.white, linestyle=hline.style_dotted)

plot(vrsi, color=color.blue, title="RSI", linewidth=2)
plot(overbought, color=color.red, title="OB Line", style=plot.style_linebr)
plot(oversold, color=color.green, title="OS Line", style=plot.style_linebr)

fill(h0, h2, color=color.red, title="Overbought Zone")
fill(h1, h2, color=color.green, title="Oversold Zone")

alertcondition(ta.crossover(vrsi, oversold), title="RSI Oversold", message="RSI: KONDISI OVERSOLD TERIDENTIFIKASI!")
alertcondition(ta.crossunder(vrsi, overbought), title="RSI Overbought", message="RSI: KONDISI OVERBOUGHT TERIDENTIFIKASI!")`,
          explanation: "RSI mengukur kekuatan relatif harga dengan membandingkan besarnya kenaikan harga terhadap besarnya penurunan. Nilai berkisar antara 0 hingga 100. Level 70 dianggap overbought, sedangkan 30 dianggap oversold.",
          usage: "Gunakan RSI untuk mengidentifikasi kondisi jenuh beli (di atas 70) dan jenuh jual (di bawah 30). Hindari entry saat overbought dalam tren turun, dan sebaliknya. Gunakan divergence (ketidaksesuaian antara harga dan RSI) sebagai sinyal pembalikan potensial.",
          tags: ["momentum", "rsi", "overbought", "oversold", "divergence"],
          source: "builtin",
          createdAt: new Date().toISOString(),
          lastModified: new Date().toISOString()
        },
        {
          id: 3,
          title: "Volume Profile",
          category: "volume",
          script: `//@version=6
indicator("Volume Profile", overlay=true)

study.shorttitle = "VP"

bins = input.int(20, title="Jumlah Level Harga", minval=5, maxval=50)
lookback = input.int(100, title="Lookback Period", minval=10)

var float[] prices = array.new_float()
var float[] volumes = array.new_float()

float priceMin = ta.lowest(low, lookback)
float priceMax = ta.highest(high, lookback)

float step = (priceMax - priceMin) / bins

// Reset arrays every bar
array.clear(prices)
array.clear(volumes)

for i = 0 to bins - 1
    array.push(prices, priceMin + step * i)
    array.push(volumes, 0.0)

// Distribute volume
for i = 0 to lookback - 1
    float p = close[i]
    float v = volume[i]
    int binIndex = math.floor((p - priceMin) / step)
    if binIndex >= 0 and binIndex < bins
        array.set(volumes, binIndex, array.get(volumes, binIndex) + v)

// Find max volume for scaling
float maxVol = array.max(volumes)
float heightFactor = 0.7 // Persentase dari chart height

for i = 0 to bins - 1
    float p = array.get(prices, i)
    float v = array.get(volumes, i)
    float barHeight = na(maxVol) or maxVol == 0 ? 0 : (v / maxVol) * heightFactor * syminfo.pointvalue * 100
    float top = p + (barHeight / 2)
    float bottom = p - (barHeight / 2)
    box.new(
        left=bar_index - 1,
        top=top,
        right=bar_index,
        bottom=bottom,
        bgcolor=color.new(color.blue, 0.6),
        border_color=color.blue,
        text=str.format("{0,number,#.#}", v),
        text_color=color.white,
        text_size=size.small
    )`,
          explanation: "Volume Profile menampilkan distribusi volume perdagangan pada level harga tertentu selama periode tertentu. Ini membantu mengidentifikasi zona nilai (value area), titik kontrol (POC), dan level penawaran/permintaan yang kuat.",
          usage: "Gunakan Volume Profile untuk menemukan level harga dengan aktivitas volume tertinggi (Point of Control) dan area di mana sebagian besar perdagangan terjadi (Value Area). Entry pada level support/resistance dengan volume tinggi cenderung lebih valid.",
          tags: ["volume", "profile", "support", "resistance", "value"],
          source: "builtin",
          createdAt: new Date().toISOString(),
          lastModified: new Date().toISOString()
        }
      ];

      // Save to storage
      saveDataToStorage();
    }

    // Filter indicators based on search and category
    function filterIndicators() {
      const searchQuery = searchInputEl.value.trim().toLowerCase();
      const categoryFilter = categoryFilterEl.value;
      
      let filtered = [...pinScriptDB, ...customDB];
      
      // Apply search filter
      if (searchQuery) {
        filtered = filtered.filter(ind => 
          ind.title.toLowerCase().includes(searchQuery) || 
          ind.explanation.toLowerCase().includes(searchQuery) || 
          ind.usage.toLowerCase().includes(searchQuery) ||
          ind.tags.some(tag => tag.toLowerCase().includes(searchQuery))
        );
      }
      
      // Apply category filter
      if (categoryFilter) {
        filtered = filtered.filter(ind => ind.category === categoryFilter);
      }
      
      return filtered;
    }

    // Render all indicators
    function renderIndicators(indicators) {
      indicatorListEl.innerHTML = '';
      
      if (indicators.length === 0) {
        indicatorListEl.innerHTML = `
          <div class="text-center py-12 bg-white/5 rounded-2xl">
            <i class="fas fa-search text-5xl text-gray-500 mb-4"></i>
            <h3 class="text-xl font-semibold text-gray-400">Tidak ditemukan</h3>
            <p class="text-gray-500">Coba sesuaikan kata pencarian atau filter Anda</p>
            <button onclick="resetFilters()" class="mt-4 bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg transition-colors">
              Reset Filter
            </button>
          </div>
        `;
        return;
      }

      // Sort by title
      indicators.sort((a, b) => a.title.localeCompare(b.title));
      
      indicators.forEach(indicator => {
        const isFavorited = favorites.includes(indicator.id);
        const isMyIndicator = myIndicators.includes(indicator.id);
        const showCloudTag = indicator.source === 'cloud';
        
        // Highlight search terms
        let title = indicator.title;
        let explanation = indicator.explanation;
        let usage = indicator.usage;
        const searchTerm = searchInputEl.value.trim().toLowerCase();
        
        if (searchTerm) {
          const regex = new RegExp(`(${searchTerm})`, 'gi');
          title = title.replace(regex, '<span class="search-highlight">$1</span>');
          explanation = explanation.replace(regex, '<span class="search-highlight">$1</span>');
          usage = usage.replace(regex, '<span class="search-highlight">$1</span>');
        }

        const indicatorCard = document.createElement('div');
        indicatorCard.className = 'indicator-card bg-white/10 backdrop-blur-md rounded-2xl p-6 border border-white/10 hover:bg-white/20 transition-all duration-300';
        
        // Create cloud sync status indicator if needed
        let syncStatus = '';
        if (showCloudTag) {
          syncStatus = `<span class="ml-2 px-2 py-1 bg-blue-500/20 text-blue-300 text-xs rounded-full">Cloud</span>`;
        }
        
        // For custom indicators
        if (indicator.source === 'custom') {
          syncStatus += ` <span class="ml-1 px-2 py-1 bg-purple-500/20 text-purple-300 text-xs rounded-full">Custom</span>`;
        }

        indicatorCard.innerHTML = `
          <div class="flex justify-between items-start mb-4">
            <h3 class="text-xl font-bold">${title}${syncStatus}</h3>
            <div class="flex space-x-2">
              <button onclick="copyScript(${indicator.id})" class="p-2 bg-white/10 hover:bg-white/20 rounded-lg transition-colors" title="Salin Script">
                <i class="fas fa-copy"></i>
              </button>
              <button onclick="toggleFavorite(${indicator.id})" class="p-2 rounded-lg transition-colors ${isFavorited ? 'text-yellow-400 bg-yellow-400/20' : 'text-gray-400 hover:text-yellow-400 hover:bg-yellow-400/10'}" title="${isFavorited ? 'Hapus dari Favorit' : 'Tambah ke Favorit'}">
                <i class="fas fa-heart"></i>
              </button>
              ${isMyIndicator ? `<button onclick="editIndicator(${indicator.id})" class="p-2 text-blue-400 hover:text-blue-300 bg-blue-400/20 rounded-lg transition-colors" title="Edit Indikator">
                <i class="fas fa-edit"></i>
              </button>` : ''}
            </div>
          </div>

          <div class="mb-4">
            <span class="inline-block bg-blue-500/20 text-blue-300 text-xs px-3 py-1 rounded-full mb-2">
              ${getCategoryLabel(indicator.category)}
            </span>
            <p class="text-gray-300">${explanation}</p>
          </div>

          <details class="mb-4 bg-black/20 rounded-lg overflow-hidden">
            <summary class="cursor-pointer px-4 py-3 bg-white/5 hover:bg-white/10 transition-colors flex justify-between items-center font-medium">
              <span>📘 Metode Penggunaan</span>
              <i class="fas fa-angle-down transition-transform duration-200"></i>
            </summary>
            <div class="px-4 pb-4 pt-2">
              <p class="text-gray-300">${usage}</p>
            </div>
          </details>

          <details class="mb-4 bg-black/20 rounded-lg overflow-hidden">
            <summary class="cursor-pointer px-4 py-3 bg-white/5 hover:bg-white/10 transition-colors flex justify-between items-center font-medium">
              <span>💻 Script PineScript V6</span>
              <i class="fas fa-angle-down transition-transform duration-200"></i>
            </summary>
            <div class="px-4 pb-4 pt-2">
              <pre class="code-block">${indicator.script}</pre>
            </div>
          </details>

          <div class="flex flex-wrap gap-2">
            ${indicator.tags.map(tag => `<span class="text-xs bg-white/5 text-gray-300 px-2 py-1 rounded">${tag}</span>`).join('')}
            <span class="text-xs bg-white/10 text-gray-300 px-2 py-1 rounded">Dibuat: ${new Date(indicator.createdAt).toLocaleDateString('id-ID')}</span>
          </div>
        `;
        
        // Rotate icon on details toggle
        const details = indicatorCard.querySelectorAll('details');
        details.forEach(detail => {
          const summary = detail.querySelector('summary');
          const icon = summary.querySelector('i');
          
          if (icon) {
            detail.addEventListener('toggle', () => {
              if (detail.open) {
                icon.classList.remove('fa-angle-down');
                icon.classList.add('fa-angle-up');
              } else {
                icon.classList.remove('fa-angle-up');
                icon.classList.add('fa-angle-down');
              }
            });
          }
        });

        indicatorListEl.appendChild(indicatorCard);
      });
    }

    // Render favorites list
    function renderFavorites() {
      favoritesListEl.innerHTML = '';
      
      if (favorites.length === 0) {
        favoritesListEl.innerHTML = '<p class="text-gray-400 text-sm">Belum ada favorit</p>';
        favoritesCountEl.textContent = '0';
        return;
      }
      
      const favoriteIndicators = [...pinScriptDB, ...customDB].filter(ind => favorites.includes(ind.id));
      
      // Sort by title
      favoriteIndicators.sort((a, b) => a.title.localeCompare(b.title));
      
      favoriteIndicators.forEach(ind => {
        const item = document.createElement('div');
        item.className = 'flex items-center justify-between text-sm text-gray-300 bg-white/5 rounded px-2 py-1';
        item.innerHTML = `
          <span class="truncate">${ind.title}</span>
          <button onclick="toggleFavorite(${ind.id})" class="text-yellow-400 hover:text-yellow-300">
            <i class="fas fa-heart"></i>
          </button>
        `;
        favoritesListEl.appendChild(item);
      });
      
      favoritesCountEl.textContent = favoriteIndicators.length;
    }

    // Render my indicators list
    function renderMyIndicators() {
      myIndicatorsListEl.innerHTML = '';
      
      if (myIndicators.length === 0) {
        myIndicatorsListEl.innerHTML = '<p class="text-gray-400 text-sm">Tidak ada indikator pribadi</p>';
        myIndicatorsCountEl.textContent = '0';
        return;
      }
      
      const myIndicatorItems = [...pinScriptDB, ...customDB].filter(ind => myIndicators.includes(ind.id));
      
      // Sort by title
      myIndicatorItems.sort((a, b) => a.title.localeCompare(b.title));
      
      myIndicatorItems.forEach(ind => {
        const item = document.createElement('div');
        item.className = 'flex items-center justify-between text-sm text-gray-300 bg-white/5 rounded px-2 py-1';
        item.innerHTML = `
          <span class="truncate">${ind.title}</span>
          ${ind.source === 'custom' ? `<button onclick="editIndicator(${ind.id})" class="text-blue-400 hover:text-blue-300">
            <i class="fas fa-edit"></i>
          </button>` : ''}
        `;
        myIndicatorsListEl.appendChild(item);
      });
      
      myIndicatorsCountEl.textContent = myIndicatorItems.length;
    }

    // Get category label
    function getCategoryLabel(category) {
      const labels = {
        trend: 'Indikator Tren',
        oscillator: 'Oscillator',
        volume: 'Volume',
        volatility: 'Volatilitas',
        pattern: 'Pola & Strategi',
        custom: 'Custom Indikator'
      };
      return labels[category] || category;
    }

    // Update statistics
    function updateStats() {
      totalIndicatorsEl.textContent = pinScriptDB.length + customDB.length;
    }

    // Toggle favorite status
    function toggleFavorite(id) {
      const index = favorites.indexOf(id);
      if (index === -1) {
        favorites.push(id);
        showToast('Ditambahkan ke favorit!');
      } else {
        favorites.splice(index, 1);
        showToast('Dihapus dari favorit!');
      }
      
      saveDataToStorage();
      renderIndicators(filterIndicators());
      renderFavorites();
    }

    // Copy script to clipboard
    function copyScript(id) {
      const indicator = [...pinScriptDB, ...customDB].find(ind => ind.id === id);
      navigator.clipboard.writeText(indicator.script)
        .then(() => {
          showToast('Script disalin ke clipboard!');
        })
        .catch(err => {
          console.error('Could not copy text: ', err);
          showToast('Gagal menyalin script', true);
        });
    }

    // Open add indicator modal
    function openAddModal() {
      addIndicatorModal.classList.remove('hidden');
      document.body.style.overflow = 'hidden';
    }

    // Edit an indicator
    function editIndicator(id) {
      const indicator = [...customDB, ...pinScriptDB].find(ind => ind.id === id);
      if (!indicator || indicator.source !== 'custom') {
        showToast('Hanya indikator custom yang bisa diedit', true);
        return;
      }
      
      // Fill the form with existing data
      document.getElementById('indicatorTitle').value = indicator.title;
      document.getElementById('indicatorCategory').value = indicator.category;
      document.getElementById('indicatorScript').value = indicator.script;
      document.getElementById('indicatorExplanation').value = indicator.explanation;
      document.getElementById('indicatorUsage').value = indicator.usage;
      document.getElementById('indicatorTags').value = indicator.tags.join(', ');
      document.getElementById('shareWithCommunity').checked = true;
      
      // Change form behavior for edit
      const form = document.getElementById('addIndicatorForm');
      form.setAttribute('data-edit-id', id);
      
      const modalTitle = addIndicatorModal.querySelector('h3');
      modalTitle.textContent = 'Edit Indikator';
      
      const submitBtn = form.querySelector('button[type="submit"]');
      submitBtn.textContent = 'Perbarui Indikator';
      
      openAddModal();
    }

    // Close add indicator modal
    function closeAddModal() {
      addIndicatorModal.classList.add('hidden');
      document.body.style.overflow = '';
      
      // Reset form
      const form = document.getElementById('addIndicatorForm');
      form.reset();
      form.removeAttribute('data-edit-id');
      
      const modalTitle = addIndicatorModal.querySelector('h3');
      modalTitle.textContent = 'Tambah Indikator Baru';
      
      const submitBtn = form.querySelector('button[type="submit"]');
      submitBtn.textContent = 'Tambahkan ke Kamus';
    }

    // Handle add indicator form submission
    function handleAddIndicator(e) {
      e.preventDefault();
      
      const editId = this.getAttribute('data-edit-id');
      const isEdit = editId !== null;
      
      const title = document.getElementById('indicatorTitle').value.trim();
      const category = document.getElementById('indicatorCategory').value;
      const script = document.getElementById('indicatorScript').value.trim();
      const explanation = document.getElementById('indicatorExplanation').value.trim();
      const usage = document.getElementById('indicatorUsage').value.trim();
      const tagsInput = document.getElementById('indicatorTags').value.trim();
      
      // Validate required fields
      if (!title || !category || !script || !explanation || !usage) {
        showToast('Semua field yang ditandai * wajib diisi', true);
        return;
      }
      
      // Parse tags
      const tags = tagsInput ? tagsInput.split(',').map(tag => tag.trim()).filter(tag => tag) : [];
      
      if (isEdit) {
        // Find and update the indicator
        const indicatorIndex = customDB.findIndex(ind => ind.id == editId);
        if (indicatorIndex !== -1) {
          customDB[indicatorIndex] = {
            ...customDB[indicatorIndex],
            title,
            category,
            script,
            explanation,
            usage,
            tags,
            lastModified: new Date().toISOString()
          };
          
          showToast('Indikator berhasil diperbarui!');
        } else {
          showToast('Gagal memperbarui indikator', true);
          return;
        }
      } else {
        // Create new indicator
        const newId = Date.now();
        const newIndicator = {
          id: newId,
          title,
          category,
          script,
          explanation,
          usage,
          tags,
          source: 'custom',
          createdAt: new Date().toISOString(),
          lastModified: new Date().toISOString()
        };
        
        customDB.push(newIndicator);
        myIndicators.push(newId);
        
        // Add to favorites if desired (optional)
        // favorites.push(newId);
        
        showToast('Indikator baru berhasil ditambahkan!');
      }
      
      // Save to storage
      if (saveDataToStorage()) {
        // Close modal and refresh view
        closeAddModal();
        renderIndicators(filterIndicators());
        renderMyIndicators();
        renderFavorites();
        updateStats();
        
        // If sharing with community is checked, queue for cloud sync
        const shareWithCommunity = document.getElementById('shareWithCommunity').checked;
        if (shareWithCommunity && !isEdit) {
          queueForCloudSync({
            id: isEdit ? editId : customDB[customDB.length-1].id,
            title,
            category,
            explanation,
            tags,
            createdAt: new Date().toISOString(),
            shared: true
          });
        }
      }
    }

    // Queue an indicator for cloud synchronization
    function queueForCloudSync(indicatorData) {
      try {
        let syncQueue = JSON.parse(localStorage.getItem('pinescript_sync_queue_v6') || '[]');
        syncQueue.push({
          ...indicatorData,
          queuedAt: new Date().toISOString(),
          status: 'pending'
        });
        
        localStorage.setItem('pinescript_sync_queue_v6', JSON.stringify(syncQueue));
        cloudStatusEl.textContent = 'Menunggu sinkronisasi cloud...';
        
        // Try to sync immediately if possible
        if (!syncInProgress) {
          setTimeout(performSync, 1000);
        }
      } catch (error) {
        console.error('Failed to queue for cloud sync:', error);
      }
    }

    // Perform synchronization with cloud
    async function performSync() {
      if (syncInProgress) return;
      
      syncInProgress = true;
      
      // Show sync modal
      syncModal.classList.remove('hidden');
      syncTitle.textContent = 'Menyinkronkan Data';
      syncMessage.textContent = 'Menghubungkan dengan server cloud...';
      syncProgress.style.width = '10%';
      syncDetails.innerHTML = '';
      syncIcon.classList.add('syncing');
      
      try {
        // Simulate network delay
        await sleep(1000);
        
        // Update status
        syncMessage.textContent = 'Memeriksa pembaruan dari server...';
        syncProgress.style.width = '25%';
        addSyncDetail('✔️ Terhubung dengan server cloud');
        
        // Simulate checking for updates
        await sleep(1000);
        
        // In a real implementation, we would:
        // 1. Fetch updates from the API
        // 2. Check for new indicators from the community
        // 3. Upload user's indicators
        // 4. Handle conflicts
        
        // For demo purposes, just simulate the process
        const updatesAvailable = Math.random() > 0.7; // 30% chance of updates
        const userUploads = JSON.parse(localStorage.getItem('pinescript_sync_queue_v6') || '[]');
        
        if (userUploads.length > 0) {
          syncMessage.textContent = `Mengunggah ${userUploads.length} indikator ke cloud...`;
          syncProgress.style.width = '50%';
          addSyncDetail(`📝 Mengunggah ${userUploads.length} indikator baru`);
          
          await sleep(1500);
          
          // Mark all as uploaded
          userUploads.forEach(item => {
            item.status = 'uploaded';
            item.uploadedAt = new Date().toISOString();
          });
          
          localStorage.setItem('pinescript_sync_queue_v6', JSON.stringify(userUploads));
          addSyncDetail('✅ Semua indikator berhasil diunggah');
          
          // Show notification
          cloudNotification.classList.remove('hidden');
          setTimeout(() => {
            cloudNotification.classList.add('hidden');
          }, 5000);
        }
        
        if (updatesAvailable) {
          syncMessage.textContent = 'Mengunduh pembaruan dari komunitas...';
          syncProgress.style.width = '75%';
          addSyncDetail('📥 Menemukan 2 indikator baru dari komunitas');
          
          // Simulate adding new community indicators
          await sleep(1500);
          
          // In real implementation, we would fetch these from the API
          // For demo, we'll just create mock data
          const communityIndicators = [
            {
              id: Date.now() + 1,
              title: "Community Trend Finder V2",
              category: "trend",
              script: "// Community contributed script\n//@version=6\nindicator(\"Community Trend Finder V2\", overlay=true)\n// ...",
              explanation: "Indikator tren yang dikembangkan oleh komunitas untuk mendeteksi perubahan tren lebih awal.",
              usage: "Gunakan sebagai konfirmasi tren utama. Bekerja paling baik pada time frame 1H ke atas.",
              tags: ["community", "trend", "advance"],
              source: "cloud",
              createdAt: new Date().toISOString(),
              lastModified: new Date().toISOString()
            },
            {
              id: Date.now() + 2,
              title: "Volume Flow Detector",
              category: "volume",
              script: "// Community contributed script\n//@version=6\nindicator(\"Volume Flow Detector\", overlay=false)\n// ...",
              explanation: "Mendeteksi aliran volume besar yang bisa menunjukkan akumulasi atau distribusi institusi.",
              usage: "Gunakan sebagai filter untuk entry. Volume besar dengan harga naik menunjukkan pembelian agresif.",
              tags: ["community", "volume", "breakout"],
              source: "cloud",
              createdAt: new Date().toISOString(),
              lastModified: new Date().toISOString()
            }
          ];
          
          // Add to main DB
          pinScriptDB.unshift(...communityIndicators);
          
          addSyncDetail('✅ Pembaruan berhasil diinstal');
        }
        
        // Finalize sync
        syncMessage.textContent = 'Sinkronisasi selesai!';
        syncProgress.style.width = '100%';
        addSyncDetail('🔄 Sinkronisasi lokal dan cloud berhasil');
        
        // Save updated DB
        saveDataToStorage();
        
        // Update UI
        setTimeout(() => {
          syncModal.classList.add('hidden');
          syncIcon.classList.remove('syncing');
          
          renderIndicators(filterIndicators());
          renderMyIndicators();
          renderFavorites();
          updateStats();
          
          syncStatusDetails.textContent = 'Terakhir disinkron: ' + new Date().toLocaleTimeString('id-ID');
          connectionStatus.className = 'w-2 h-2 bg-green-500 rounded-full';
          showToast('Sinkronisasi berhasil!');
          
          syncInProgress = false;
        }, 1000);
        
      } catch (error) {
        console.error('Sync failed:', error);
        syncTitle.textContent = 'Gagal Menyinkronkan';
        syncMessage.textContent = 'Terjadi kesalahan saat menyinkronkan data';
        syncProgress.style.width = '100%';
        addSyncDetail(`❌ ${error.message}`);
        syncIcon.classList.remove('syncing');
        
        connectionStatus.className = 'w-2 h-2 bg-red-500 rounded-full';
        syncStatusDetails.textContent = 'Kesalahan koneksi';
        
        setTimeout(() => {
          syncModal.classList.add('hidden');
          syncInProgress = false;
        }, 2000);
        
        showToast('Gagal menyinkronkan data', true);
      }
    }

    // Add detail to sync process display
    function addSyncDetail(text) {
      const p = document.createElement('p');
      p.className = 'text-xs text-gray-400 mt-1';
      p.textContent = text;
      syncDetails.appendChild(p);
      
      // Auto scroll to bottom
      syncDetails.scrollTop = syncDetails.scrollHeight;
    }

    // Show toast notification
    function showToast(message, isError = false) {
      toastMessageEl.textContent = message;
      toastIconEl.className = isError ? 'fas fa-exclamation-circle mr-2' : 'fas fa-check-circle mr-2';
      toastEl.className = `fixed bottom-6 right-6 bg-${isError ? 'red' : 'green'}-600 text-white px-6 py-3 rounded-xl shadow-lg transform opacity-100 translate-y-0 transition-all duration-300`;
      
      setTimeout(() => {
        toastEl.className = 'fixed bottom-6 right-6 bg-green-600 text-white px-6 py-3 rounded-xl shadow-lg hidden transition-all duration-300 transform opacity-0 translate-y-4';
      }, 3000);
    }

    // Utility sleep function
    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }

    // Reset filters
    function resetFilters() {
      searchInputEl.value = '';
      categoryFilterEl.value = '';
      renderIndicators(filterIndicators());
    }

    // Event Listeners
    searchInputEl.addEventListener('input', () => {
      renderIndicators(filterIndicators());
    });

    categoryFilterEl.addEventListener('change', () => {
      renderIndicators(filterIndicators());
    });

    syncBtn.addEventListener('click', performSync);
    addIndicatorBtn.addEventListener('click', openAddModal);

    // Form submission
    const addForm = document.getElementById('addIndicatorForm');
    addForm.addEventListener('submit', handleAddIndicator);

    // Keyboard navigation
    document.addEventListener('keydown', (e) => {
      // Escape key closes modal
      if (e.key === 'Escape') {
        closeAddModal();
      }
    });

    // Make functions globally available
    window.toggleFavorite = toggleFavorite;
    window.copyScript = copyScript;
    window.openAddModal = openAddModal;
    window.closeAddModal = closeAddModal;
    window.editIndicator = editIndicator;
    window.resetFilters = resetFilters;

    // Initialize on load
    window.addEventListener('load', init);
  </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-qwensite.hf.space/logo.svg" alt="qwensite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-qwensite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >QwenSite</a> - 🧬 <a href="https://enzostvs-qwensite.hf.space?remix=alterzick/library" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>