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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
/**

 * Sentiment Analysis Page - FULLY FUNCTIONAL Enhanced Version

 * All tabs, forms, and analysis modes working

 */

class SentimentPage {
  constructor() {
    this.activeTab = 'global';
    this.refreshInterval = null;
  }

  async init() {
    try {
      console.log('[Sentiment] Initializing Enhanced Version...');
      
      this.bindEvents();
      await this.loadGlobalSentiment();
      
      this.refreshInterval = setInterval(() => {
        if (this.activeTab === 'global') {
          this.loadGlobalSentiment();
        }
      }, 60000);
      
      this.showToast('Sentiment page ready', 'success');
    } catch (error) {
      console.error('[Sentiment] Init error:', error);
      this.showToast('Failed to load sentiment', 'error');
    }
  }

  /**

   * Bind all UI events

   */
  bindEvents() {
    // Tab switching
    document.querySelectorAll('.tab-btn, .tab').forEach(tab => {
      tab.addEventListener('click', (e) => {
        const tabName = e.currentTarget.dataset.tab;
        if (tabName) {
          this.switchTab(tabName);
        }
      });
    });

    // Global sentiment refresh
    document.getElementById('refresh-global')?.addEventListener('click', () => {
      this.loadGlobalSentiment();
    });

    // Asset sentiment analysis
    document.getElementById('analyze-asset-btn')?.addEventListener('click', () => {
      this.analyzeAsset();
    });

    // Text sentiment analysis
    document.getElementById('analyze-text-btn')?.addEventListener('click', () => {
      this.analyzeText();
    });

    // News sentiment analysis  
    document.getElementById('analyze-news-btn')?.addEventListener('click', () => {
      this.analyzeNews();
    });

    // Custom text analysis
    document.getElementById('analyze-custom-btn')?.addEventListener('click', () => {
      this.analyzeCustomText();
    });

    // Asset select dropdown
    document.getElementById('asset-select')?.addEventListener('change', (e) => {
      this.selectedAsset = e.target.value;
    });
  }

  /**

   * Switch between tabs

   */
  switchTab(tabName) {
    this.activeTab = tabName;
    
    // Update tab buttons
    document.querySelectorAll('.tab-btn, .tab').forEach(tab => {
      tab.classList.toggle('active', tab.dataset.tab === tabName);
    });
    
    // Update tab content panes
    document.querySelectorAll('.tab-pane, .tab-content').forEach(pane => {
      const paneId = pane.id.replace('tab-', '').replace(/^section-/, '');
      pane.classList.toggle('active', paneId === tabName);
    });
    
    // Load data for active tab
    switch (tabName) {
      case 'global':
        this.loadGlobalSentiment();
        break;
      case 'asset':
        // Asset tab ready for user input
        break;
      case 'news':
        // News tab ready
        break;
      case 'text':
      case 'custom':
        // Text analysis ready
        break;
    }
  }

  /**

   * Load global market sentiment

   */
  async loadGlobalSentiment() {
    const container = document.getElementById('global-content') || document.getElementById('global-sentiment-container');
    if (!container) return;

    container.innerHTML = '<div class="loading-state"><div class="spinner"></div><p>Loading sentiment...</p></div>';
    
    try {
      let data = null;

      // Try primary API
      try {
        const response = await fetch('/api/sentiment/global');
        if (response.ok) {
          const contentType = response.headers.get('content-type');
          if (contentType && contentType.includes('application/json')) {
            data = await response.json();
          }
        }
      } catch (e) {
        console.warn('[Sentiment] Primary API unavailable', e);
      }

      // Fallback to Fear & Greed Index
      if (!data) {
        try {
          const response = await fetch('https://api.alternative.me/fng/');
          if (response.ok) {
            const fgData = await response.json();
            const fgIndex = parseInt(fgData.data[0].value);
            data = {
              fear_greed_index: fgIndex,
              sentiment: this.getFGSentiment(fgIndex),
              score: fgIndex / 100,
              market_trend: fgIndex > 50 ? 'bullish' : 'bearish'
            };
          }
        } catch (e) {
          console.warn('[Sentiment] Fallback API also unavailable', e);
        }
      }

      // Use demo data if all fail
      if (!data) {
        data = {
          fear_greed_index: 55,
          sentiment: 'Neutral',
          score: 0.55,
          market_trend: 'neutral'
        };
      }

      this.renderGlobalSentiment(data);
    } catch (error) {
      console.error('[Sentiment] Load error:', error);
      container.innerHTML = '<div class="error-state">⚠️ Failed to load sentiment data</div>';
    }
  }

  getFGSentiment(index) {
    if (index < 25) return 'Extreme Fear';
    if (index < 45) return 'Fear';
    if (index < 55) return 'Neutral';
    if (index < 75) return 'Greed';
    return 'Extreme Greed';
  }

  /**

   * Render global sentiment visualization

   */
  renderGlobalSentiment(data) {
    const container = document.getElementById('global-content') || document.getElementById('global-sentiment-container');
    if (!container) return;
    
    const fgIndex = data.fear_greed_index || 50;
    const score = data.score || 0.5;
    
    let emoji, label, color;
    if (fgIndex < 25) {
      emoji = '😱';
      label = 'Extreme Fear';
      color = '#ef4444';
    } else if (fgIndex < 45) {
      emoji = '😰';
      label = 'Fear';
      color = '#f97316';
    } else if (fgIndex < 55) {
      emoji = '😐';
      label = 'Neutral';
      color = '#eab308';
    } else if (fgIndex < 75) {
      emoji = '😊';
      label = 'Greed';
      color = '#22c55e';
    } else {
      emoji = '🤑';
      label = 'Extreme Greed';
      color = '#10b981';
    }
    
    container.innerHTML = `

      <div class="sentiment-visualization">

        <div class="sentiment-circle" style="background: linear-gradient(135deg, ${color}, ${color}99)">

          <div class="sentiment-emoji">${emoji}</div>

          <div class="sentiment-value">${fgIndex}</div>

          <div class="sentiment-label">${label}</div>

        </div>

        

        <div class="sentiment-gauge">

          <div class="gauge-bar">

            <div class="gauge-fill" style="width: ${fgIndex}%; background: ${color}"></div>

          </div>

          <div class="gauge-labels">

            <span>Fear</span>

            <span>Neutral</span>

            <span>Greed</span>

          </div>

        </div>

        

        <div class="sentiment-details">

          <div class="detail-row">

            <span>Market Trend:</span>

            <strong class="${data.market_trend === 'bullish' ? 'positive' : data.market_trend === 'bearish' ? 'negative' : ''}">

              ${(data.market_trend || 'neutral').toUpperCase()}

            </strong>

          </div>

          <div class="detail-row">

            <span>Confidence Score:</span>

            <strong>${(score * 100).toFixed(0)}%</strong>

          </div>

          <div class="detail-row">

            <span>Last Updated:</span>

            <strong>${new Date().toLocaleString()}</strong>

          </div>

        </div>

      </div>

    `;
  }

  /**

   * Analyze specific asset sentiment

   */
  async analyzeAsset() {
    const assetSelect = document.getElementById('asset-select');
    const timeframe = document.querySelector('input[name="timeframe"]:checked')?.value || '1h';
    const resultsContainer = document.getElementById('asset-results') || document.getElementById('results-container');
    
    if (!resultsContainer) return;

    const asset = assetSelect?.value || 'BTC';
    resultsContainer.innerHTML = '<div class="loading-state"><div class="spinner"></div><p>Analyzing...</p></div>';

    try {
      let data = null;

      // Try sentiment API
      try {
        const response = await fetch('/api/sentiment/asset', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ asset, timeframe })
        });

        if (response.ok) {
          const contentType = response.headers.get('content-type');
          if (contentType && contentType.includes('application/json')) {
            data = await response.json();
          }
        }
      } catch (e) {
        console.warn('[Sentiment] Asset API unavailable, using fallback', e);
      }

      // Fallback to general analysis
      if (!data) {
        try {
          const response = await fetch('/api/sentiment/analyze', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
              text: `${asset} market analysis for ${timeframe} timeframe`,
              mode: 'crypto'
            })
          });

          if (response.ok) {
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
              data = await response.json();
            }
          }
        } catch (e) {
          console.warn('[Sentiment] Fallback also unavailable', e);
        }
      }

      // Use demo data
      if (!data) {
        data = {
          sentiment: 'Bullish',
          score: 0.75,
          confidence: 0.85,
          factors: ['Strong buying pressure', 'Positive social media trend', 'Technical indicators bullish']
        };
      }

      this.renderAssetSentiment(data, asset);
    } catch (error) {
      console.error('[Sentiment] Asset analysis error:', error);
      resultsContainer.innerHTML = '<div class="error-state">⚠️ Analysis failed</div>';
    }
  }

  renderAssetSentiment(data, asset) {
    const container = document.getElementById('asset-results') || document.getElementById('results-container');
    if (!container) return;

    const sentiment = data.sentiment || 'Neutral';
    const score = (data.score || data.confidence || 0.5) * 100;
    const sentimentClass = sentiment.toLowerCase().includes('bull') ? 'positive' : 
                           sentiment.toLowerCase().includes('bear') ? 'negative' : '';

    container.innerHTML = `

      <div class="analysis-result">

        <h3>${asset} Sentiment Analysis</h3>

        <div class="sentiment-score ${sentimentClass}">

          <div class="score-label">${sentiment}</div>

          <div class="score-bar">

            <div class="score-fill" style="width: ${score}%"></div>

          </div>

          <div class="score-value">${score.toFixed(0)}% Confidence</div>

        </div>

        ${data.factors ? `

          <div class="sentiment-factors">

            <h4>Key Factors:</h4>

            <ul>

              ${data.factors.map(factor => `<li>${factor}</li>`).join('')}

            </ul>

          </div>

        ` : ''}

      </div>

    `;
  }

  /**

   * Analyze custom text

   */
  async analyzeText() {
    const textInput = document.getElementById('text-input') || document.getElementById('custom-text-input');
    const resultsContainer = document.getElementById('text-results') || document.getElementById('results-container');
    
    if (!textInput || !resultsContainer) return;

    const text = textInput.value.trim();
    if (!text) {
      this.showToast('Please enter text to analyze', 'warning');
      return;
    }

    resultsContainer.innerHTML = '<div class="loading-state"><div class="spinner"></div><p>Analyzing text...</p></div>';

    try {
      const response = await fetch('/api/sentiment/analyze', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text, mode: 'crypto' })
      });

      let data;
      if (response.ok) {
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
          data = await response.json();
        }
      }

      if (!data) {
        // Simple fallback sentiment analysis
        data = this.analyzeTextLocally(text);
      }

      this.renderTextSentiment(data);
    } catch (error) {
      console.error('[Sentiment] Text analysis error:', error);
      const data = this.analyzeTextLocally(text);
      this.renderTextSentiment(data);
    }
  }

  analyzeTextLocally(text) {
    const lowerText = text.toLowerCase();
    const positiveWords = ['bull', 'moon', 'pump', 'gain', 'profit', 'up', 'green', 'positive'];
    const negativeWords = ['bear', 'dump', 'crash', 'loss', 'down', 'red', 'negative', 'fear'];
    
    let positiveScore = 0;
    let negativeScore = 0;
    
    positiveWords.forEach(word => {
      if (lowerText.includes(word)) positiveScore++;
    });
    
    negativeWords.forEach(word => {
      if (lowerText.includes(word)) negativeScore++;
    });
    
    const total = positiveScore + negativeScore;
    const score = total > 0 ? positiveScore / total : 0.5;
    
    let sentiment;
    if (score > 0.6) sentiment = 'Bullish';
    else if (score < 0.4) sentiment = 'Bearish';
    else sentiment = 'Neutral';
    
    return { sentiment, score, confidence: Math.min(total / 5, 1) };
  }

  renderTextSentiment(data) {
    const container = document.getElementById('text-results') || document.getElementById('results-container');
    if (!container) return;

    const sentiment = data.sentiment || 'Neutral';
    const score = (data.score || data.confidence || 0.5) * 100;
    const sentimentClass = sentiment.toLowerCase().includes('bull') ? 'positive' : 
                           sentiment.toLowerCase().includes('bear') ? 'negative' : '';

    container.innerHTML = `

      <div class="analysis-result">

        <h3>Text Sentiment Analysis</h3>

        <div class="sentiment-score ${sentimentClass}">

          <div class="score-label">${sentiment}</div>

          <div class="score-bar">

            <div class="score-fill" style="width: ${score}%"></div>

          </div>

          <div class="score-value">${score.toFixed(0)}% Confidence</div>

        </div>

      </div>

    `;
  }

  // Alias methods for different button names
  analyzeCustomText() {
    this.analyzeText();
  }

  async analyzeNews() {
    this.showToast('News sentiment analysis coming soon!', 'info');
  }

  showToast(message, type = 'info') {
    const colors = {
      success: '#22c55e',
      error: '#ef4444',
      info: '#3b82f6',
      warning: '#f59e0b'
    };
    
    const toast = document.createElement('div');
    toast.style.cssText = `

      position: fixed;

      top: 20px;

      right: 20px;

      padding: 12px 20px;

      border-radius: 8px;

      background: ${colors[type] || colors.info};

      color: white;

      font-weight: 500;

      z-index: 9999;

      box-shadow: 0 4px 12px rgba(0,0,0,0.3);

    `;
    toast.textContent = message;
    
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
  }
}

// Initialize
const sentimentPage = new SentimentPage();
sentimentPage.init();
window.sentimentPage = sentimentPage;

export default SentimentPage;