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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e2f664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1301d4
 
 
 
 
 
 
 
 
 
 
 
4e2f664
 
 
 
e1301d4
 
 
 
 
 
 
 
 
 
 
 
 
4e2f664
 
 
e1301d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e2f664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1301d4
 
 
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
/**

 * Lo-fi Focus Timer — Main Script

 * ═══════════════════════════════════════════════════════════════════════════

 * A minimal, elegant pomodoro timer with lo-fi vibes

 * Made with 💙 by Kai

 * ═══════════════════════════════════════════════════════════════════════════

 */

(function () {
    "use strict";

    // ═══════════════════════════════════════════════════════════════════════
    // CONSTANTS
    // ═══════════════════════════════════════════════════════════════════════

    // Mutable for custom durations
    let MODES = {
        focus: { time: 25, label: "Focus Time", color: "focus" },
        short: { time: 5, label: "Short Break", color: "short" },
        long: { time: 15, label: "Long Break", color: "long" }
    };

    // Ambient sounds 🌙
    const AMBIENT_SOUNDS = {
        rain: { name: "Rain", file: "sounds/rain.mp3" },
        fire: { name: "Fire", file: "sounds/fire.mp3" },
        cafe: { name: "Café", file: "sounds/cafe.mp3" },
        forest: { name: "Forest", file: "sounds/forest.mp3" },
        waves: { name: "Waves", file: "sounds/waves.mp3" },
        thunder: { name: "Thunder", file: "sounds/thunder.mp3" }
    };

    const RING_CIRCUMFERENCE = 565.48; // 2 * π * 90
    const SESSIONS_BEFORE_LONG_BREAK = 4;

    // Radio stations 🎵
    const RADIO_STATIONS = {
        // === Lo-Fi & Chill ===
        "lofi-girl": {
            name: "☕ Lofi Girl",
            url: "https://play.streamafrica.net/lofiradio"
        },
        chillhop: {
            name: "🎧 Chillhop",
            url: "https://streams.fluxfm.de/Chillhop/mp3-320"
        },
        "jazz-lofi": {
            name: "🎷 Jazz Lo-Fi",
            url: "https://streams.fluxfm.de/jazzradio/mp3-320"
        },
        // === FIP (Radio France) ===
        "fip-groove": {
            name: "🎸 FIP Groove",
            url: "https://icecast.radiofrance.fr/fipgroove-midfi.mp3"
        },
        "fip-jazz": {
            name: "🎺 FIP Jazz",
            url: "https://icecast.radiofrance.fr/fipjazz-midfi.mp3"
        },
        "fip-electro": {
            name: "🎹 FIP Electro",
            url: "https://icecast.radiofrance.fr/fipelectro-midfi.mp3"
        },
        "fip-world": {
            name: "🌍 FIP World",
            url: "https://icecast.radiofrance.fr/fipworld-midfi.mp3"
        },
        "fip-pop": {
            name: "🎤 FIP Pop",
            url: "https://icecast.radiofrance.fr/fippop-midfi.mp3"
        },
        // === Ambient & Focus ===
        "soma-drone": {
            name: "🌌 SomaFM Drone",
            url: "https://ice1.somafm.com/dronezone-128-mp3"
        },
        "soma-space": {
            name: "🚀 SomaFM Space",
            url: "https://ice1.somafm.com/spacestation-128-mp3"
        },
        "soma-groove": {
            name: "🎶 SomaFM Groove",
            url: "https://ice1.somafm.com/groovesalad-128-mp3"
        }
    };

    // ═══════════════════════════════════════════════════════════════════════
    // STATE
    // ═══════════════════════════════════════════════════════════════════════

    let state = {
        mode: "focus",
        timeRemaining: MODES.focus.time * 60, // in seconds
        totalTime: MODES.focus.time * 60,
        isRunning: false,
        sessionCount: 1,
        intervalId: null,
        settings: {
            soundEnabled: true,
            autoStartBreaks: false,
            effectsEnabled: true
        },
        radio: {
            isPlaying: false,
            currentStation: "fip-groove",
            volume: 0.5
        },
        ambient: {
            active: [], // Multiple sounds can play
            volume: 0.3
        },
        customDurations: {
            focus: 25,
            short: 5,
            long: 15
        },
        notificationsEnabled: false
    };

    // Audio element for radio
    let radioAudio = null;

    // Ambient audio elements (one per sound type)
    let ambientAudios = {};

    // Single AudioContext for notifications (avoid memory leaks)
    let audioContext = null;

    // ═══════════════════════════════════════════════════════════════════════
    // BROWSER NOTIFICATIONS 🔔
    // ═══════════════════════════════════════════════════════════════════════

    function requestNotificationPermission() {
        if (!("Notification" in window)) {
            console.log("🔔 Notifications not supported");
            alert("🔔 Browser notifications are not supported on your device.");
            return;
        }

        if (Notification.permission === "granted") {
            state.notificationsEnabled = true;
        } else if (Notification.permission === "denied") {
            alert("🚫 Notifications are blocked. Please enable them in your browser settings.");
            if (elements.notifToggle) elements.notifToggle.checked = false;
        } else if (Notification.permission !== "denied") {
            Notification.requestPermission().then(permission => {
                state.notificationsEnabled = permission === "granted";
                if (elements.notifToggle) {
                    elements.notifToggle.checked = state.notificationsEnabled;
                }
                if (permission === "denied") {
                    alert("🚫 Notifications blocked. You can enable them later in settings.");
                }
                saveSettings();
            });
        }
    }

    function sendNotification(title, body) {
        if (!state.notificationsEnabled || Notification.permission !== "granted") return;

        try {
            const notif = new Notification(title, {
                body: body,
                icon: "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>",
                badge: "⚡",
                tag: "lofi-focus-timer",
                silent: true // We have our own sound
            });

            // Auto-close after 5 seconds
            setTimeout(() => notif.close(), 5000);

            // Click to focus the window
            notif.onclick = () => {
                window.focus();
                notif.close();
            };
        } catch (e) {
            console.log("🔔 Notification failed:", e);
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // AMBIENT SOUNDS 🌙
    // ═══════════════════════════════════════════════════════════════════════

    function initAmbient() {
        // Don't pre-create all audios — create them on-demand to save memory!
        // Just load saved settings
        loadAmbientSettings();
    }

    function getOrCreateAmbientAudio(soundKey) {
        // Lazy creation: only create audio when first used
        if (!ambientAudios[soundKey]) {
            const audio = new Audio();
            audio.loop = true;
            audio.volume = state.ambient.volume;
            audio.src = AMBIENT_SOUNDS[soundKey].file;
            audio.preload = "metadata";
            ambientAudios[soundKey] = audio;
            console.log(`🎵 Created audio for: ${AMBIENT_SOUNDS[soundKey].name}`);
        }
        return ambientAudios[soundKey];
    }

    function toggleAmbientSound(soundKey) {
        const audio = getOrCreateAmbientAudio(soundKey);
        const btn = document.querySelector(`.ambient-btn[data-sound="${soundKey}"]`);

        if (!audio || !btn) return;

        if (state.ambient.active.includes(soundKey)) {
            // Stop this sound
            audio.pause();
            audio.currentTime = 0;
            state.ambient.active = state.ambient.active.filter(s => s !== soundKey);
            btn.classList.remove("active");
            btn.setAttribute("aria-pressed", "false");
            console.log(`🌙 Stopped: ${AMBIENT_SOUNDS[soundKey].name}`);

            // Update visualizer connection
            updateVisualizerConnection();
        } else {
            // Play this sound - src already set in initAmbient()
            audio.volume = state.ambient.volume;

            // Show loading state
            btn.classList.add("loading");

            audio
                .play()
                .then(() => {
                    // Remove loading, add active
                    btn.classList.remove("loading");
                    btn.classList.add("active");
                    btn.setAttribute("aria-pressed", "true");
                    state.ambient.active.push(soundKey);
                    console.log(`🌙 Playing: ${AMBIENT_SOUNDS[soundKey].name}`);

                    // Connect to visualizer if this is the first/only active sound
                    updateVisualizerConnection();
                })
                .catch(e => {
                    console.log(`🌙 Could not play ${soundKey}:`, e.message);
                    btn.classList.remove("loading");
                    btn.classList.add("error");
                    setTimeout(() => btn.classList.remove("error"), 2000);
                });
        }

        saveAmbientSettings();
    }

    // Connect the best audio source to visualizer 🎵⚡
    function updateVisualizerConnection() {
        if (typeof window.connectAudioVisualizer !== "function") return;

        // Priority: Radio > First active ambient sound
        if (state.radio.isPlaying && radioAudio) {
            window.connectAudioVisualizer(radioAudio);
            return;
        }

        // Try first active ambient sound
        if (state.ambient.active.length > 0) {
            const firstActiveKey = state.ambient.active[0];
            const audio = ambientAudios[firstActiveKey];
            if (audio && !audio.paused) {
                window.connectAudioVisualizer(audio);
                console.log(`🎵 Visualizer connected to: ${AMBIENT_SOUNDS[firstActiveKey].name}`);
                return;
            }
        }

        // Nothing playing, disconnect
        if (typeof window.disconnectAudioVisualizer === "function") {
            window.disconnectAudioVisualizer();
        }
    }

    function setAmbientVolume(value) {
        state.ambient.volume = value / 100;
        Object.values(ambientAudios).forEach(audio => {
            audio.volume = state.ambient.volume;
        });
        saveAmbientSettings();
    }

    function loadAmbientSettings() {
        try {
            const saved = localStorage.getItem("lofi-focus-ambient");
            if (saved) {
                const settings = JSON.parse(saved);
                state.ambient.volume = settings.volume ?? 0.3;
                if (elements.ambientVolume) {
                    elements.ambientVolume.value = state.ambient.volume * 100;
                }
            }
        } catch (e) {
            console.log("🌙 Could not load ambient settings");
        }
    }

    function saveAmbientSettings() {
        clearTimeout(saveAmbientTimeout);
        saveAmbientTimeout = setTimeout(() => {
            try {
                localStorage.setItem(
                    "lofi-focus-ambient",
                    JSON.stringify({
                        volume: state.ambient.volume
                    })
                );
            } catch (e) {
                console.log("🌙 Could not save ambient settings");
            }
        }, 500); // Save after 500ms of inactivity
    }

    // ═══════════════════════════════════════════════════════════════════════
    // CUSTOM TIMER DURATIONS 🎨
    // ═══════════════════════════════════════════════════════════════════════

    function updateCustomDuration(mode, value) {
        const duration = parseInt(value, 10);
        // Validate: 1-120 for focus, 1-60 for long, 1-30 for short
        const maxDurations = { focus: 120, short: 30, long: 60 };
        const maxDuration = maxDurations[mode] || 120;

        if (isNaN(duration) || duration < 1 || duration > maxDuration) {
            // Reset to previous valid value
            const input = document.getElementById(`${mode}-duration`);
            if (input) input.value = state.customDurations[mode];
            return;
        }

        state.customDurations[mode] = duration;
        MODES[mode].time = duration;

        // Update button text
        const btn = document.querySelector(`.mode-btn[data-mode="${mode}"]`);
        if (btn) {
            const timeSpan = btn.querySelector(".mode-time");
            if (timeSpan) timeSpan.textContent = `${duration}m`;
        }

        // If current mode, update timer
        if (state.mode === mode && !state.isRunning) {
            state.totalTime = duration * 60;
            state.timeRemaining = state.totalTime;
            updateDisplay();
        }

        saveSettings();
        console.log(`⏱️ ${mode} duration set to ${duration} min`);
    }

    // ═══════════════════════════════════════════════════════════════════════
    // DOM ELEMENTS
    // ═══════════════════════════════════════════════════════════════════════

    const elements = {
        minutes: document.getElementById("minutes"),
        seconds: document.getElementById("seconds"),
        sessionType: document.getElementById("session-type"),
        sessionNumber: document.getElementById("session-number"),
        btnStart: document.getElementById("btn-start"),
        btnPause: document.getElementById("btn-pause"),
        btnReset: document.getElementById("btn-reset"),
        btnSettings: document.getElementById("btn-settings"),
        settingsPanel: document.getElementById("settings-panel"),
        soundToggle: document.getElementById("sound-toggle"),
        autoStartToggle: document.getElementById("auto-start"),
        effectsToggle: document.getElementById("effects-toggle"),
        progressRing: document.querySelector(".progress-ring__progress"),
        timerSection: document.querySelector(".timer-section"),
        modeButtons: document.querySelectorAll(".mode-btn"),
        // Radio elements
        btnRadio: document.getElementById("btn-radio"),
        radioIcon: document.getElementById("radio-icon"),
        radioStatus: document.getElementById("radio-status"),
        radioSelect: document.getElementById("radio-select"),
        radioVolume: document.getElementById("radio-volume"),
        radioPlayer: document.querySelector(".radio-player"),
        // Ambient elements
        ambientButtons: document.querySelectorAll(".ambient-btn"),
        ambientVolume: document.getElementById("ambient-volume"),
        // Notifications & custom durations
        notifToggle: document.getElementById("notif-toggle"),
        focusDuration: document.getElementById("focus-duration"),
        shortDuration: document.getElementById("short-duration"),
        longDuration: document.getElementById("long-duration")
    };

    // ═══════════════════════════════════════════════════════════════════════
    // RADIO PLAYER 🎵
    // ═══════════════════════════════════════════════════════════════════════

    function initRadio() {
        radioAudio = new Audio();
        radioAudio.volume = state.radio.volume;
        radioAudio.crossOrigin = "anonymous";

        radioAudio.addEventListener("playing", () => {
            state.radio.isPlaying = true;
            updateRadioUI();
            console.log("🎵 Radio playing:", RADIO_STATIONS[state.radio.currentStation].name);
        });

        radioAudio.addEventListener("pause", () => {
            state.radio.isPlaying = false;
            updateRadioUI();
        });

        radioAudio.addEventListener("error", e => {
            console.log("🎵 Radio error, trying to reconnect...", e);
            state.radio.isPlaying = false;
            updateRadioUI();
            elements.radioStatus.textContent = "Connection error";
        });

        radioAudio.addEventListener("waiting", () => {
            elements.radioStatus.textContent = "Buffering...";
        });

        radioAudio.addEventListener("canplay", () => {
            if (state.radio.isPlaying) {
                elements.radioStatus.textContent = "Now Playing";
            }
        });

        // Load saved radio settings
        loadRadioSettings();
    }

    function toggleRadio() {
        if (state.radio.isPlaying) {
            stopRadio();
        } else {
            playRadio();
        }
    }

    function playRadio() {
        const station = RADIO_STATIONS[state.radio.currentStation];
        if (!station) return;

        elements.radioStatus.textContent = "Connecting...";
        elements.radioPlayer.classList.add("loading"); // Visual feedback!
        radioAudio.src = station.url;
        radioAudio
            .play()
            .then(() => {
                elements.radioPlayer.classList.remove("loading");
                // Update visualizer connection (radio has priority)
                updateVisualizerConnection();
            })
            .catch(e => {
                console.log("🎵 Autoplay blocked, user interaction needed");
                elements.radioStatus.textContent = "Click to play";
                elements.radioPlayer.classList.remove("loading");
                elements.radioPlayer.classList.add("error");
                setTimeout(() => elements.radioPlayer.classList.remove("error"), 2000);
            });
    }

    function stopRadio() {
        radioAudio.pause();
        radioAudio.src = "";
        state.radio.isPlaying = false;
        updateRadioUI();
        // Update visualizer (might switch to ambient if playing)
        updateVisualizerConnection();
        console.log("🎵 Radio stopped");
    }

    function changeStation(stationId) {
        state.radio.currentStation = stationId;
        saveRadioSettings();

        if (state.radio.isPlaying) {
            playRadio();
        }
    }

    function setVolume(value) {
        state.radio.volume = value / 100;
        if (radioAudio) {
            radioAudio.volume = state.radio.volume;
        }
        saveRadioSettings();
    }

    function updateRadioUI() {
        if (state.radio.isPlaying) {
            elements.btnRadio.classList.add("playing");
            elements.radioPlayer.classList.add("playing");
            elements.radioStatus.classList.add("playing");
            elements.radioIcon.textContent = "🔊";
            elements.radioStatus.textContent = "Now Playing";
        } else {
            elements.btnRadio.classList.remove("playing");
            elements.radioPlayer.classList.remove("playing");
            elements.radioStatus.classList.remove("playing");
            elements.radioIcon.textContent = "🎵";
            elements.radioStatus.textContent = "Radio Off";
        }
    }

    function loadRadioSettings() {
        try {
            const saved = localStorage.getItem("lofi-focus-radio");
            if (saved) {
                const settings = JSON.parse(saved);
                state.radio = { ...state.radio, ...settings };
                elements.radioSelect.value = state.radio.currentStation;
                elements.radioVolume.value = state.radio.volume * 100;
                if (radioAudio) {
                    radioAudio.volume = state.radio.volume;
                }
            }
        } catch (e) {
            console.log("🎵 Could not load radio settings");
        }
    }

    // Debounce helper for localStorage writes
    let saveRadioTimeout;
    let saveAmbientTimeout;

    function saveRadioSettings() {
        clearTimeout(saveRadioTimeout);
        saveRadioTimeout = setTimeout(() => {
            try {
                localStorage.setItem(
                    "lofi-focus-radio",
                    JSON.stringify({
                        currentStation: state.radio.currentStation,
                        volume: state.radio.volume
                    })
                );
            } catch (e) {
                console.log("🎵 Could not save radio settings");
            }
        }, 500); // Save after 500ms of inactivity
    }

    // ═══════════════════════════════════════════════════════════════════════
    // AUDIO (simple beep using Web Audio API)
    // ═══════════════════════════════════════════════════════════════════════

    function getAudioContext() {
        if (!audioContext || audioContext.state === "closed") {
            audioContext = new (window.AudioContext || window.webkitAudioContext)();
        }
        // Resume if suspended (browser autoplay policy)
        if (audioContext.state === "suspended") {
            audioContext.resume();
        }
        return audioContext;
    }

    function playBeep(frequency = 800, duration = 0.3, delay = 0) {
        try {
            const ctx = getAudioContext();
            const startTime = ctx.currentTime + delay;

            const oscillator = ctx.createOscillator();
            const gainNode = ctx.createGain();

            oscillator.connect(gainNode);
            gainNode.connect(ctx.destination);

            oscillator.frequency.value = frequency;
            oscillator.type = "sine";

            gainNode.gain.setValueAtTime(0.3, startTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, startTime + duration);

            oscillator.start(startTime);
            oscillator.stop(startTime + duration);
        } catch (e) {
            console.log("⚡ Audio not supported");
        }
    }

    function playNotificationSound() {
        if (!state.settings.soundEnabled) return;

        // Play 3 beeps with slight delays
        playBeep(800, 0.3, 0);
        playBeep(800, 0.3, 0.2);
        playBeep(1000, 0.4, 0.4); // Last beep slightly higher
    }

    // ═══════════════════════════════════════════════════════════════════════
    // TIMER LOGIC
    // ═══════════════════════════════════════════════════════════════════════

    function startTimer() {
        if (state.isRunning) return;

        state.isRunning = true;
        elements.timerSection.classList.remove("timer-paused");
        updateControlButtons();

        state.intervalId = setInterval(() => {
            state.timeRemaining--;

            if (state.timeRemaining <= 0) {
                timerComplete();
            } else {
                updateDisplay();
            }
        }, 1000);

        console.log("⚡ Timer started!");
    }

    function pauseTimer() {
        if (!state.isRunning) return;

        state.isRunning = false;
        elements.timerSection.classList.add("timer-paused");
        clearInterval(state.intervalId);
        updateControlButtons();

        console.log("⏸ Timer paused");
    }

    function resetTimer() {
        pauseTimer();
        state.timeRemaining = state.totalTime;
        updateDisplay();
        console.log("↺ Timer reset");
    }

    function timerComplete() {
        pauseTimer();
        playNotificationSound();

        // Send browser notification 🔔
        const modeLabel = MODES[state.mode].label;
        if (state.mode === "focus") {
            sendNotification("⚡ Focus Complete!", "Time for a break. You earned it!");
        } else {
            sendNotification("☕ Break Over!", "Ready to focus again?");
        }

        console.log("🎉 Timer complete!");

        // Determine next mode
        if (state.mode === "focus") {
            // Long break every 4 completed focus sessions
            // Increment session count AFTER deciding break type (current session just completed)
            if (state.sessionCount % SESSIONS_BEFORE_LONG_BREAK === 0) {
                setMode("long");
            } else {
                setMode("short");
            }
            // Increment AFTER the break decision (next focus will be new session)
            state.sessionCount++;
        } else {
            // After any break, go back to focus
            setMode("focus");
        }

        // Auto-start if enabled
        if (state.settings.autoStartBreaks) {
            // Show countdown in session type
            let countdown = 3;
            const originalLabel = MODES[state.mode].label;
            const countdownInterval = setInterval(() => {
                elements.sessionType.textContent = `${originalLabel} in ${countdown}...`;
                countdown--;
                if (countdown < 0) {
                    clearInterval(countdownInterval);
                    elements.sessionType.textContent = originalLabel;
                }
            }, 1000);
            setTimeout(() => {
                startTimer();
            }, 3000); // 3 second delay
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // MODE MANAGEMENT
    // ═══════════════════════════════════════════════════════════════════════

    function setMode(mode) {
        if (!MODES[mode]) return;

        // If timer is running, pause first
        if (state.isRunning) {
            pauseTimer();
        }

        state.mode = mode;
        state.totalTime = MODES[mode].time * 60;
        state.timeRemaining = state.totalTime;

        // Update body attribute for CSS theming
        document.body.setAttribute("data-mode", mode);

        // Update session type label
        elements.sessionType.textContent = MODES[mode].label;

        // Update mode buttons
        elements.modeButtons.forEach(btn => {
            btn.classList.toggle("active", btn.dataset.mode === mode);
        });

        // Update visualizer colors! 🎨
        if (typeof window.setVisualizerMode === "function") {
            window.setVisualizerMode(mode);
        }

        updateDisplay();
        console.log(`⚡ Mode changed to: ${mode}`);
    }

    // ═══════════════════════════════════════════════════════════════════════
    // DISPLAY UPDATES
    // ═══════════════════════════════════════════════════════════════════════

    function updateDisplay() {
        const minutes = Math.floor(state.timeRemaining / 60);
        const seconds = state.timeRemaining % 60;

        elements.minutes.textContent = String(minutes).padStart(2, "0");
        elements.seconds.textContent = String(seconds).padStart(2, "0");
        elements.sessionNumber.textContent = state.sessionCount;

        updateProgressRing();
        updateDocumentTitle(minutes, seconds);
    }

    function updateProgressRing() {
        const progress = state.timeRemaining / state.totalTime;
        const offset = RING_CIRCUMFERENCE * (1 - progress);
        elements.progressRing.style.strokeDashoffset = offset;

        // Update ARIA progress for screen readers
        const progressPercent = Math.round(progress * 100);
        const progressRingSvg = document.querySelector(".progress-ring");
        if (progressRingSvg) {
            progressRingSvg.setAttribute("aria-valuenow", progressPercent);
        }
    }

    function updateDocumentTitle(minutes, seconds) {
        const timeStr = `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
        const modeEmoji = state.mode === "focus" ? "⚡" : "☕";
        document.title = `${timeStr} ${modeEmoji} Lo-fi Focus`;
    }

    function updateControlButtons() {
        if (state.isRunning) {
            elements.btnStart.classList.add("hidden");
            elements.btnPause.classList.remove("hidden");
        } else {
            elements.btnStart.classList.remove("hidden");
            elements.btnPause.classList.add("hidden");
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // SETTINGS
    // ═══════════════════════════════════════════════════════════════════════

    function toggleSettings() {
        const isHidden = elements.settingsPanel.classList.toggle("hidden");
        elements.btnSettings.setAttribute("aria-expanded", !isHidden);
    }

    function loadSettings() {
        try {
            const saved = localStorage.getItem("lofi-focus-settings");
            if (saved) {
                const parsed = JSON.parse(saved);
                state.settings = { ...state.settings, ...parsed };
                elements.soundToggle.checked = state.settings.soundEnabled;
                elements.autoStartToggle.checked = state.settings.autoStartBreaks;
                if (elements.effectsToggle) {
                    elements.effectsToggle.checked = state.settings.effectsEnabled ?? true;
                }
            }

            // Load custom durations
            const durations = localStorage.getItem("lofi-focus-durations");
            if (durations) {
                state.customDurations = { ...state.customDurations, ...JSON.parse(durations) };
                // Apply to MODES
                MODES.focus.time = state.customDurations.focus;
                MODES.short.time = state.customDurations.short;
                MODES.long.time = state.customDurations.long;
                // Update inputs
                if (elements.focusDuration) elements.focusDuration.value = state.customDurations.focus;
                if (elements.shortDuration) elements.shortDuration.value = state.customDurations.short;
                if (elements.longDuration) elements.longDuration.value = state.customDurations.long;
                // Update button labels
                document.querySelectorAll(".mode-btn").forEach(btn => {
                    const mode = btn.dataset.mode;
                    const timeSpan = btn.querySelector(".mode-time");
                    if (timeSpan && state.customDurations[mode]) {
                        timeSpan.textContent = `${state.customDurations[mode]}m`;
                    }
                });
            }

            // Load notification preference
            const notifPref = localStorage.getItem("lofi-focus-notif");
            if (notifPref === "true" && Notification.permission === "granted") {
                state.notificationsEnabled = true;
                if (elements.notifToggle) elements.notifToggle.checked = true;
            }
        } catch (e) {
            console.log("⚡ Could not load settings, using defaults");
        }
    }

    function saveSettings() {
        try {
            localStorage.setItem("lofi-focus-settings", JSON.stringify(state.settings));
            localStorage.setItem("lofi-focus-durations", JSON.stringify(state.customDurations));
            localStorage.setItem("lofi-focus-notif", state.notificationsEnabled.toString());
        } catch (e) {
            console.log("⚡ Could not save settings");
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // EVENT LISTENERS
    // ═══════════════════════════════════════════════════════════════════════

    function setupEventListeners() {
        // Timer controls
        elements.btnStart.addEventListener("click", startTimer);
        elements.btnPause.addEventListener("click", pauseTimer);
        elements.btnReset.addEventListener("click", resetTimer);

        // Mode buttons
        elements.modeButtons.forEach(btn => {
            btn.addEventListener("click", () => {
                setMode(btn.dataset.mode);
            });
        });

        // Settings
        elements.btnSettings.addEventListener("click", toggleSettings);

        elements.soundToggle.addEventListener("change", e => {
            state.settings.soundEnabled = e.target.checked;
            saveSettings();
        });

        elements.autoStartToggle.addEventListener("change", e => {
            state.settings.autoStartBreaks = e.target.checked;
            saveSettings();
        });

        if (elements.effectsToggle) {
            elements.effectsToggle.addEventListener("change", e => {
                state.settings.effectsEnabled = e.target.checked;
                toggleVisualEffects(e.target.checked);
                saveSettings();
            });
        }

        // Radio controls 🎵
        elements.btnRadio.addEventListener("click", toggleRadio);

        elements.radioSelect.addEventListener("change", e => {
            changeStation(e.target.value);
        });

        elements.radioVolume.addEventListener("input", e => {
            setVolume(e.target.value);
        });

        // Ambient sounds 🌙
        elements.ambientButtons.forEach(btn => {
            btn.addEventListener("click", () => {
                toggleAmbientSound(btn.dataset.sound);
            });
        });

        if (elements.ambientVolume) {
            elements.ambientVolume.addEventListener("input", e => {
                setAmbientVolume(e.target.value);
            });
        }

        // Browser notifications 🔔
        if (elements.notifToggle) {
            elements.notifToggle.addEventListener("change", e => {
                if (e.target.checked) {
                    requestNotificationPermission();
                } else {
                    state.notificationsEnabled = false;
                    saveSettings();
                }
            });
        }

        // Custom durations 🎨
        if (elements.focusDuration) {
            elements.focusDuration.addEventListener("change", e => {
                updateCustomDuration("focus", e.target.value);
            });
        }
        if (elements.shortDuration) {
            elements.shortDuration.addEventListener("change", e => {
                updateCustomDuration("short", e.target.value);
            });
        }
        if (elements.longDuration) {
            elements.longDuration.addEventListener("change", e => {
                updateCustomDuration("long", e.target.value);
            });
        }

        // Keyboard shortcuts
        document.addEventListener("keydown", e => {
            // Ignore if typing in an input
            if (e.target.tagName === "INPUT" || e.target.tagName === "SELECT") return;

            // Space to start/pause
            if (e.code === "Space") {
                e.preventDefault();
                state.isRunning ? pauseTimer() : startTimer();
            }
            // R to reset
            if (e.code === "KeyR") {
                e.preventDefault();
                resetTimer();
            }
            // 1, 2, 3 for modes
            if (e.code === "Digit1") setMode("focus");
            if (e.code === "Digit2") setMode("short");
            if (e.code === "Digit3") setMode("long");
            // M to toggle music/radio
            if (e.code === "KeyM") {
                e.preventDefault();
                toggleRadio();
            }
        });
    }

    // ═══════════════════════════════════════════════════════════════════════
    // VISUAL EFFECTS TOGGLE ✨
    // ═══════════════════════════════════════════════════════════════════════

    function toggleVisualEffects(enabled) {
        const canvas = document.getElementById("lightning-canvas");
        if (!canvas) return;

        if (enabled) {
            canvas.style.display = "block";
            canvas.style.opacity = "1";
            // Notify lightning.js to resume if paused
            if (typeof window.resumeVisualEffects === "function") {
                window.resumeVisualEffects();
            }
            console.log("✨ Visual effects enabled");
        } else {
            canvas.style.opacity = "0";
            // Wait for fade out, then hide
            setTimeout(() => {
                canvas.style.display = "none";
            }, 300);
            // Notify lightning.js to pause rendering
            if (typeof window.pauseVisualEffects === "function") {
                window.pauseVisualEffects();
            }
            console.log("✨ Visual effects disabled (better performance)");
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // INITIALIZATION
    // ═══════════════════════════════════════════════════════════════════════

    function init() {
        loadSettings();
        initRadio();
        initAmbient();
        setupEventListeners();
        setMode("focus");
        updateDisplay();
        setupAboutModal();
        setupShortcutsModal();

        // Apply visual effects setting
        toggleVisualEffects(state.settings.effectsEnabled);

        console.log("⚡ Lo-fi Focus Timer initialized!");
        console.log("💙 Made with love by Kai");
        console.log("─────────────────────────────────");
        console.log("Keyboard shortcuts:");
        console.log("  [Space] Start/Pause timer");
        console.log("  [R] Reset timer");
        console.log("  [1] Focus mode");
        console.log("  [2] Short break");
        console.log("  [3] Long break");
        console.log("  [M] Toggle radio 🎵");
        console.log("─────────────────────────────────");
        console.log("🌙 Ambient sounds ready");
        console.log(
            "🔔 Browser notifications: " + (Notification.permission === "granted" ? "enabled" : "click to enable")
        );
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ABOUT MODAL ⚡
    // ═══════════════════════════════════════════════════════════════════════

    function setupAboutModal() {
        const modal = document.getElementById("about-modal");
        const btnAbout = document.getElementById("btn-about");
        const btnAbout2 = document.getElementById("btn-about-2");
        const btnClose = document.getElementById("modal-close");
        const overlay = modal?.querySelector(".modal-overlay");

        if (!modal) return;

        function openModal(e) {
            e.preventDefault();
            modal.classList.remove("hidden");
            document.body.style.overflow = "hidden";
        }

        function closeModal() {
            modal.classList.add("hidden");
            document.body.style.overflow = "";
        }

        btnAbout?.addEventListener("click", openModal);
        btnAbout2?.addEventListener("click", openModal);
        btnClose?.addEventListener("click", closeModal);
        overlay?.addEventListener("click", closeModal);

        // Close on Escape key
        document.addEventListener("keydown", e => {
            if (e.key === "Escape" && !modal.classList.contains("hidden")) {
                closeModal();
            }
        });
    }

    // ═══════════════════════════════════════════════════════════════════════
    // SHORTCUTS MODAL ⌨️
    // ═══════════════════════════════════════════════════════════════════════

    function setupShortcutsModal() {
        const modal = document.getElementById("shortcuts-modal");
        const btnShortcuts = document.getElementById("btn-shortcuts");
        const btnClose = document.getElementById("shortcuts-close");
        const overlay = modal?.querySelector(".modal-overlay");

        if (!modal) return;

        function openModal(e) {
            e.preventDefault();
            modal.classList.remove("hidden");
            document.body.style.overflow = "hidden";
        }

        function closeModal() {
            modal.classList.add("hidden");
            document.body.style.overflow = "";
        }

        btnShortcuts?.addEventListener("click", openModal);
        btnClose?.addEventListener("click", closeModal);
        overlay?.addEventListener("click", closeModal);

        // Open with "?" key
        document.addEventListener("keydown", e => {
            if (e.key === "?" && modal.classList.contains("hidden")) {
                e.preventDefault();
                openModal(e);
            }
            // Close on Escape
            if (e.key === "Escape" && !modal.classList.contains("hidden")) {
                closeModal();
            }
        });
    }

    // Start the app
    init();
})();