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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// Page Transition
document.addEventListener("DOMContentLoaded", function () {
    document.body.classList.add("loaded"); // Fade-in page on load
});

// Handle link clicks for page transitions
document.querySelectorAll("a").forEach(link => {
    link.addEventListener("click", function (event) {
        if (this.getAttribute("target") === "_blank") return;

        event.preventDefault(); // Stop instant navigation
        let href = this.href;

        // Create transition element
        let overlay = document.createElement("div");
        overlay.classList.add("transition-overlay");
        document.body.appendChild(overlay);

        // Trigger expanding circle effect
        setTimeout(() => {
            overlay.classList.add("expand");
        }, 90);
        // Optional: Clean up the overlay after the animation duration
        setTimeout(() => {
            overlay.remove();
        }, 1000);

        // Navigate after transition
        setTimeout(() => {
            window.location.href = href;
        }, 890);
    });
});

// Fade-In Animation on Scroll
document.addEventListener("DOMContentLoaded", function () {
    const fadeElements = document.querySelectorAll(".fade-in");

    const checkVisibility = () => {
        fadeElements.forEach((element) => {
            const elementTop = element.getBoundingClientRect().top;
            const elementBottom = element.getBoundingClientRect().bottom;
            const isVisible = elementTop < window.innerHeight && elementBottom >= 0;

            if (isVisible) {
                element.classList.add("visible");
            }
        });
    };

    window.addEventListener("scroll", checkVisibility);
    checkVisibility(); // Check on page load
});


// Page transition & dark mode toggle
document.addEventListener("DOMContentLoaded", function () {
    document.body.classList.add("loaded");

    const darkToggle = document.getElementById("darkModeToggle");
    const toggleIcon = document.querySelector('.toggle-circle .toggle-icon');

    function updateToggleIcon() {
        if (darkToggle && toggleIcon) {
            if (darkToggle.checked) {
                toggleIcon.innerHTML = '&#9790;'; // Moon
                toggleIcon.style.color = "#4a8fdf";
            } else {
                toggleIcon.innerHTML = '&#9728;'; // Sun
                toggleIcon.style.color = "#FFD600";
            }
        }
    }

    if (darkToggle) {
        darkToggle.checked = true;
        document.body.classList.add("dark-mode");
        updateToggleIcon();

        darkToggle.addEventListener("change", () => {
            document.body.classList.toggle("dark-mode");
            updateToggleIcon();
            updatePredictionChartColors();
            
        });
    }

    document.querySelectorAll("a").forEach(link => {
        if (link.getAttribute("target") === "_blank") return;

        link.addEventListener("click", function (event) {
            event.preventDefault();
            const overlay = document.createElement("div");
            overlay.classList.add("transition-overlay");
            document.body.appendChild(overlay);

            setTimeout(() => overlay.classList.add("active"), 90);
            setTimeout(() => overlay.remove(), 1000);
            setTimeout(() => window.location.href = this.href, 890);
        });
    });
    // Set min date for prediction input
    const today = new Date();
    const minDate = new Date(today);
    minDate.setDate(today.getDate() + 6);
    const maxDate = new Date(today);
    maxDate.setMonth(today.getMonth() + 1);

    function formatDate(d) {
        const yyyy = d.getFullYear();
        const mm = String(d.getMonth() + 1).padStart(2, '0');
        const dd = String(d.getDate()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd}`;
    }

    const predictionDateInput = document.getElementById('prediction-date');
    predictionDateInput.min = formatDate(minDate);
    predictionDateInput.max = formatDate(maxDate);
});

document.addEventListener("DOMContentLoaded", function () {
    fetch("/get-companies")
      .then(response => response.json())
      .then(data => {
        const select = document.getElementById("stock-select");
        const seen = new Set(); // Track unique tickers
        data.forEach(company => {
          const ticker = company["Yahoo Finance Ticker"];
          const name = company["Company Name"];
          // Exclude NIFTY and SENSEX tickers and duplicates
          if (ticker !== "^NSEI" && ticker !== "^BSESN" && !seen.has(ticker)) {
            const option = document.createElement("option");
            option.value = ticker;
            option.textContent = name;
            select.appendChild(option);
            seen.add(ticker);
          }
        });
      })
      .catch(error => console.error("Error fetching companies:", error));
});

let predictionChart = null;
function handleEpochsChange(select) {
  const customInput = document.getElementById('custom-epochs');
  if (select.value === 'custom') {
    customInput.style.display = 'block';
    customInput.focus();
  } else {
    customInput.style.display = 'none';
  }
}window.handleEpochsChange = handleEpochsChange;

// Listen for the "Predict" button click and route prediction request based on radio button
document.getElementById('predict-btn').addEventListener('click', async function (e) {
    e.preventDefault();
    const stockSymbol = document.getElementById('stock-select').value;
    const predictionType = document.querySelector('input[name="data-source"]:checked').value;
    const predictionDate = document.getElementById('prediction-date').value;

    if (!stockSymbol) {
        showMessage("Please select a stock", true);
        return;
    }

    if (!predictionDate) {
        showMessage("Please select a prediction date", true);
        return;
    }
    // Date validation
    const selected = new Date(predictionDate);
    const today = new Date();
    const min = new Date(today);
    min.setDate(today.getDate() + 6); // 6 days minimum
    const max = new Date(today);
    max.setMonth(today.getMonth() + 1);

    selected.setHours(0,0,0,0);
    min.setHours(0,0,0,0);
    max.setHours(0,0,0,0);

    if (selected < min || selected > max) {
        showMessage("Prediction date must be at least 6 days from today and at most 1 month from today.", true);
        return;
    }
    let epochs;
    const epochsSelect = document.getElementById('epochs');
    if (epochsSelect.value === 'custom') {
        epochs = document.getElementById('custom-epochs').value || 100;
    } else {
        epochs = epochsSelect.value;
    }

    // Show loading overlay and start progress
    document.getElementById('loading-overlay').style.display = "flex";
    updateProgress(0);

    this.disabled = true;
    this.textContent = "Predicting...";

    let payload = {
        ticker: stockSymbol,
        type: predictionType,
        prediction_date: predictionDate,
        epochs: epochs
    };

    // Set progress duration based on prediction type
    let progress = 0;
    let intervalMs;
    let maxProgress = 95;
    if (predictionType === "both") {
        // Double the time for both pipelines (~130 seconds)
        intervalMs = 51000; // 100% / 130s = ~1% per 1.3s
    } else if (predictionType === "news-sentiment") {
        // About 79 seconds for sentiment pipeline
        intervalMs = 27000; // 100% / 79s = ~1% per 0.79s
    } else {
        intervalMs = 18000; // ~65 seconds for single pipeline
    }
    let progressInterval = setInterval(() => {
        if (progress < maxProgress) {
            progress += 1;
            updateProgress(progress);
        }
    }, intervalMs);

    try {
        const response = await fetch('/predict-result', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        clearInterval(progressInterval);
        updateProgress(100);

        const result = await response.json();

        setTimeout(() => {
            document.getElementById('loading-overlay').style.display = "none";
        }, 400);

        if (response.ok) {
            displayPredictionResults(result);
        } else {
            showMessage(result.error || "Prediction failed", true);
        }
    } catch (error) {
        clearInterval(progressInterval);
        document.getElementById('loading-overlay').style.display = "none";
        showMessage("An error occurred", true);
    }

    this.disabled = false;
    this.textContent = "Predict Stock Price";
});

function updateProgress(percent) {
    document.getElementById('progress-text').textContent = `Loading... ${percent}%`;
}
function displayPredictionResults(prediction) {
    // If both, render two graphs in separate areas with space
    if (prediction.historical && prediction.sentiment) {
        document.getElementById('result-section').style.display = "block";
        document.getElementById('result-stock-name').textContent = prediction.historical.stock;
        document.getElementById('predicted-price').textContent = prediction.historical.predictedPrice;

        // Clear and create two separate chart areas with spacing
        const chartContainer = document.querySelector('.chart-container');
        chartContainer.innerHTML = `
            <div class="graph-area" id="graph-area-historical">
                <h4 style="margin-bottom:12px;">Historical Only</h4>
                <div id="prediction-chart-historical" style="height: 450px;"></div>
            </div>
            <div class="graph-area" id="graph-area-sentiment">
                <h4 style="margin-bottom:12px;">With Sentiment</h4>
                <div id="prediction-chart-sentiment" style="height: 450px;"></div>
            </div>
        `;

        renderPredictionChart(prediction.historical, 'prediction-chart-historical', 'Historical Only');
        renderPredictionChart(prediction.sentiment, 'prediction-chart-sentiment', 'With Sentiment');
    } else {
        // Single pipeline as before
        document.getElementById('result-stock-name').textContent = prediction.stock;
        document.getElementById('predicted-price').textContent = prediction.predictedPrice;
        document.getElementById('result-section').style.display = "block";
        renderPredictionChart(prediction, 'prediction-chart');
    }
}

function renderPredictionChart(prediction, chartId = 'prediction-chart', customTitle = null) {
    const data = [];

    // Train data (from historicalData)
    const trainLabels = prediction.historicalData.map(d => d.date);
    const trainValues = prediction.historicalData.map(d => d.price);
    data.push({
        x: trainLabels,
        y: trainValues,
        mode: 'lines',
        name: 'Train Data',
        fill: 'tozeroy',
        line: { color: 'rgba(74,143,223,1)' }
    });

    // Actual price (validation/test) from actualVsPredicted
    const validLabels = prediction.actualVsPredicted.map(d => d.date);
    const actualValues = prediction.actualVsPredicted.map(d => d.actual);
    data.push({
        x: validLabels,
        y: actualValues,
        mode: 'lines',
        name: 'Actual Price',
        fill: 'tozeroy',
        line: { color: 'green', width: 2 }
    });

    // Predicted price (validation/test) from actualVsPredicted
    const predictedValues = prediction.actualVsPredicted.map(d => d.predicted);
    data.push({
        x: validLabels,
        y: predictedValues,
        mode: 'lines',
        name: 'Predicted Price',
        fill: 'tozeroy',
        line: { color: 'red', width: 3, dash: 'dot' }
    });

    // Future predictions
    if (prediction.futureDates && prediction.futurePrices) {
        data.push({
            x: prediction.futureDates,
            y: prediction.futurePrices,
            mode: 'lines+markers',
            name: 'Future Predictions',
            fill: 'tozeroy',
            line: { color: 'orange', width: 2, dash: 'dash' },
            marker: { size: 8, color: 'orange' }
        });
    }

    // Buy signals
    if (prediction.buySignals && prediction.buySignals.points) {
        const buyPoints = prediction.buySignals.points;
        const buyReasons = prediction.buySignals.reasons || [];
        const buyIndices = prediction.buyIndices || Array.from({length: buyPoints.length}, (_, i) => i);
        const buyDates = buyIndices.map(idx => prediction.futureDates[idx] || '');

        data.push({
            x: buyDates,
            y: buyPoints,
            mode: 'markers',
            name: 'Buy Signals',
            marker: {
                color: 'cyan',
                size: 12,
                symbol: 'star',
                line: { width: 2, color: 'black' }
            },
            text: buyReasons,
            hovertemplate: '<b>Buy Signal</b><br>Date: %{x}<br>Price: ₹%{y:,.2f}<br>Reason: %{text}<extra></extra>'
        });
    }

    // Layout (unchanged)
    const getTextColor = () => '#A0AEC0';
    const getGridColor = () => 'rgba(105,123,147,0.4)';
    const getBgColor = () => 'rgba(19,27,43,0.0)';
    const layout = {
        title: customTitle || 'Stock Price Prediction with Future Forecast & Buy Signals',
        xaxis: {
            title: 'Date',
            color: getTextColor(),
            gridcolor: getGridColor(),
            spikecolor: "rgba(105,123,147,255)",
            spikedash: "solid",
            spikethickness: -2
        },
        yaxis: {
            title: 'Stock Price',
            color: getTextColor(),
            gridcolor: getGridColor(),
            tickprefix: '₹',
            tickformat: ',',
            spikecolor: "rgba(105,123,149,255)",
            spikedash: "solid",
            spikethickness: -2,
            zeroline: false
        },
        paper_bgcolor: getBgColor(),
        plot_bgcolor: getBgColor(),
        font: { color: getTextColor() },
        margin: { t: 50, b: 50, l: 50, r: 20 },
        legend: { x: 0, y: 1 },
        hovermode: "closest"
    };
    

    Plotly.newPlot(chartId, data, layout, { responsive: true });
}
window.renderPredictionChart = renderPredictionChart; 
function updatePredictionChartColors() {
    const layoutUpdate = {
        paper_bgcolor: getBgColor(),
        plot_bgcolor: getBgColor(),
        font: { color: getTextColor() },
        xaxis: { color: getTextColor(), gridcolor: getGridColor() },
        yaxis: { color: getTextColor(), gridcolor: getGridColor() }
    };
    Plotly.relayout('prediction-chart', layoutUpdate);
}
function getTextColor() {
    return document.body.classList.contains("dark-mode") ? '#fff' : '#333';
}

function getGridColor() {
    return document.body.classList.contains("dark-mode") ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.05)';
}

function getBgColor() {
    return document.body.classList.contains("dark-mode") ? '#1e2a38' : '#fff';
}

function showMessage(message, isError = false) {
    let box = document.getElementById("message-box");
    if (!box) {
        box = document.createElement("div");
        box.id = "message-box";
        // Place above the Predict button
        const btn = document.getElementById('predict-btn');
        btn.parentNode.insertBefore(box, btn);
    }
    box.style.position = "static";
    box.style.marginBottom = "16px";
    box.style.padding = "10px 18px";
    box.style.borderRadius = "6px";
    box.style.zIndex = "1";
    box.style.fontSize = "15px";
    box.style.boxShadow = "0 4px 12px rgba(0,0,0,0.08)";
    box.style.backgroundColor = isError ? "#ffe6e6" : "#e0f7fa";
    box.style.color = isError ? "#c62828" : "#00796b";
    box.style.border = `1px solid ${isError ? "#c62828" : "#00796b"}`;
    box.style.display = "inline-block";
    box.style.maxWidth = "320px";
    box.style.textAlign = "center";
    box.style.whiteSpace = "normal";
    box.style.wordBreak = "break-word";
    box.style.marginLeft = "auto";
    box.style.marginRight = "auto";
    box.textContent = message;

    setTimeout(() => { box.style.display = "none"; }, 4000);
}


// Disclaimer close logic
document.addEventListener("DOMContentLoaded", function() {
  const closeBtn = document.getElementById("close-disclaimer");
  if (closeBtn) {
    closeBtn.onclick = function() {
      document.getElementById("disclaimer-overlay").style.display = "none";
    };
  }
});
document.addEventListener("DOMContentLoaded", function () {
    // Hide disclaimer by default
    document.getElementById("disclaimer-overlay").style.display = "none";

    function showDisclaimer() {
        document.getElementById("disclaimer-overlay").style.display = "flex";
    }

    // Only show tutorial if not seen before
    if (!localStorage.getItem("predictorTutorialSeen")) {
        setTimeout(() => {
            introJs().setOptions({
                nextLabel: 'Next',
                prevLabel: 'Back',
                skipLabel: 'Skip',
                doneLabel: 'Done',
                overlayOpacity: 0.7,
                showProgress: true,
                tooltipClass: 'custom-introjs-tooltip'
            }).oncomplete(function() {
                localStorage.setItem("predictorTutorialSeen", "yes");
                showDisclaimer();
            }).onexit(function() {
                localStorage.setItem("predictorTutorialSeen", "yes");
                showDisclaimer();
            }).start();
        }, 600); // Wait for page to load
    } else {
        // If tutorial already seen, show disclaimer immediately
        showDisclaimer();
    }

    // Disclaimer close logic
    const closeBtn = document.getElementById("close-disclaimer");
    if (closeBtn) {
        closeBtn.onclick = function() {
            document.getElementById("disclaimer-overlay").style.display = "none";
        };
    }
});

document.addEventListener('DOMContentLoaded', function () {
    const sentimentContainer = document.getElementById('news-sentiment');
    const sentimentText = document.getElementById('sentiment-text');
    const radioButtons = document.querySelectorAll('input[name="data-source"]');

    // Function to map sentiment values to text
    function mapSentimentValueToText(value) {
        switch (value) {
            case 0:
                return "Negative";
            case 1:
                return "Neutral";
            case 2:
                return "Positive";
            default:
                return "Unknown";
        }
    }

    // Function to fetch and display news sentiment
    async function fetchNewsSentiment(stockSymbol) {
        try {
            const response = await fetch(`/api/news-sentiment?ticker=${stockSymbol}`);
            const data = await response.json();
            if (response.ok && data.sentiment !== undefined) {
                const sentimentTextValue = mapSentimentValueToText(data.sentiment);
                sentimentText.textContent = `Sentiment: ${sentimentTextValue}`;
            } else {
                sentimentText.textContent = 'No sentiment data available.';
            }
        } catch (error) {
            sentimentText.textContent = 'Error fetching sentiment data.';
            console.error('Error fetching sentiment:', error);
        }
    }

    // Event listener for radio button changes
    radioButtons.forEach(radio => {
        radio.addEventListener('change', function () {
            const stockSymbol = document.getElementById('stock-select').value;
            if ((this.value === 'news-sentiment' || this.value === 'both') && stockSymbol) {
                sentimentContainer.style.display = 'block';
                fetchNewsSentiment(stockSymbol);
            } else {
                sentimentContainer.style.display = 'none';
            }
        });
    });

    // Trigger sentiment fetch after prediction
    document.getElementById('predict-btn').addEventListener('click', function () {
        const selectedRadio = document.querySelector('input[name="data-source"]:checked');
        const stockSymbol = document.getElementById('stock-select').value;
        if (selectedRadio && (selectedRadio.value === 'news-sentiment' || selectedRadio.value === 'both')) {
            sentimentContainer.style.display = 'block';
            fetchNewsSentiment(stockSymbol);
        } else {
            sentimentContainer.style.display = 'none';
        }
    });
});

import { initializeNewsletterForm } from './newsletter.js';
document.addEventListener("DOMContentLoaded", function () {
    initializeNewsletterForm();
    // Other page-specific code...
});