"use client" import React, { useState } from 'react' const layouts = (process.env.NEXT_PUBLIC_TRADINGVIEW_LAYOUTS || 'ai,Diy module').split(',').map(l => l.trim()) const timeframes = [ { label: '1m', value: '1' }, { label: '5m', value: '5' }, { label: '15m', value: '15' }, { label: '1h', value: '60' }, { label: '4h', value: '240' }, { label: '1d', value: 'D' }, { label: '1w', value: 'W' }, { label: '1M', value: 'M' }, ] const popularCoins = [ { name: 'Bitcoin', symbol: 'BTCUSD', icon: 'โ‚ฟ', color: 'from-orange-400 to-orange-600' }, { name: 'Ethereum', symbol: 'ETHUSD', icon: 'ฮž', color: 'from-blue-400 to-blue-600' }, { name: 'Solana', symbol: 'SOLUSD', icon: 'โ—Ž', color: 'from-purple-400 to-purple-600' }, { name: 'Sui', symbol: 'SUIUSD', icon: '๐Ÿ”ท', color: 'from-cyan-400 to-cyan-600' }, { name: 'Avalanche', symbol: 'AVAXUSD', icon: '๐Ÿ”บ', color: 'from-red-400 to-red-600' }, { name: 'Cardano', symbol: 'ADAUSD', icon: 'โ™ ', color: 'from-indigo-400 to-indigo-600' }, { name: 'Polygon', symbol: 'MATICUSD', icon: '๐Ÿ”ท', color: 'from-violet-400 to-violet-600' }, { name: 'Chainlink', symbol: 'LINKUSD', icon: '๐Ÿ”—', color: 'from-blue-400 to-blue-600' }, ] export default function AIAnalysisPanel() { const [symbol, setSymbol] = useState('BTCUSD') const [selectedLayouts, setSelectedLayouts] = useState(['ai', 'diy']) // Default to both AI and DIY const [selectedTimeframes, setSelectedTimeframes] = useState(['60']) // Support multiple timeframes const [loading, setLoading] = useState(false) const [result, setResult] = useState(null) const [error, setError] = useState(null) // Helper function to safely render any value const safeRender = (value: any): string => { if (typeof value === 'string') return value if (typeof value === 'number') return value.toString() if (Array.isArray(value)) return value.join(', ') if (typeof value === 'object' && value !== null) { return JSON.stringify(value) } return String(value) } const toggleLayout = (layout: string) => { setSelectedLayouts(prev => prev.includes(layout) ? prev.filter(l => l !== layout) : [...prev, layout] ) } const toggleTimeframe = (timeframe: string) => { setSelectedTimeframes(prev => prev.includes(timeframe) ? prev.filter(tf => tf !== timeframe) : [...prev, timeframe] ) } const performAnalysis = async (analysisSymbol = symbol, analysisTimeframes = selectedTimeframes) => { if (loading || selectedLayouts.length === 0 || analysisTimeframes.length === 0) return setLoading(true) setError(null) setResult(null) try { if (analysisTimeframes.length === 1) { // Single timeframe analysis const response = await fetch('/api/enhanced-screenshot', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ symbol: analysisSymbol, timeframe: analysisTimeframes[0], layouts: selectedLayouts, analyze: true }) }) const data = await response.json() if (!response.ok) { throw new Error(data.error || 'Analysis failed') } setResult(data) } else { // Multiple timeframe analysis const results = [] for (const tf of analysisTimeframes) { console.log(`๐Ÿงช Analyzing timeframe: ${timeframes.find(t => t.value === tf)?.label || tf}`) const response = await fetch('/api/enhanced-screenshot', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ symbol: analysisSymbol, timeframe: tf, layouts: selectedLayouts, analyze: true }) }) const result = await response.json() results.push({ timeframe: tf, timeframeLabel: timeframes.find(t => t.value === tf)?.label || tf, success: response.ok, result }) // Small delay between requests await new Promise(resolve => setTimeout(resolve, 2000)) } setResult({ type: 'multi_timeframe', symbol: analysisSymbol, summary: `Analyzed ${results.length} timeframes for ${analysisSymbol}`, results }) } } catch (err) { setError(err instanceof Error ? err.message : 'Failed to perform analysis') } finally { setLoading(false) } } const quickAnalyze = async (coinSymbol: string, quickTimeframes = selectedTimeframes) => { setSymbol(coinSymbol) if (!loading) { await performAnalysis(coinSymbol, quickTimeframes) } } const quickTimeframeTest = async (testTimeframe: string) => { // Toggle the timeframe in selection instead of replacing const newTimeframes = selectedTimeframes.includes(testTimeframe) ? selectedTimeframes.filter(tf => tf !== testTimeframe) : [...selectedTimeframes, testTimeframe] setSelectedTimeframes(newTimeframes) if (!loading && symbol && newTimeframes.length > 0) { await performAnalysis(symbol, newTimeframes) } } const testAllTimeframes = async () => { if (loading) return const allTimeframeValues = timeframes.map(tf => tf.value) setSelectedTimeframes(allTimeframeValues) if (!loading && symbol) { await performAnalysis(symbol, allTimeframeValues) } } async function handleAnalyze() { await performAnalysis() } return (

๐Ÿค– AI Chart Analysis

AI Powered
{/* Quick Coin & Timeframe Analysis */}

Quick Analysis

Select coin + timeframe combo for instant analysis
{/* Quick Timeframe Presets */}
{/* Coin Selection */}
{popularCoins.map(coin => ( ))}
{/* Advanced Controls */}

Advanced Analysis

{/* Symbol Input */}
setSymbol(e.target.value.toUpperCase())} placeholder="e.g., BTCUSD, ETHUSD" />
{/* Timeframe Selection */}
{timeframes.map(tf => ( ))}
{selectedTimeframes.length > 0 && (
Selected timeframes: {selectedTimeframes.map(tf => timeframes.find(t => t.value === tf)?.label).join(', ')}
๐Ÿ’ก Multiple timeframes provide broader market outlook
)}
{/* Layout Selection */}
{layouts.map(layout => ( ))}
{selectedLayouts.length > 0 && (
Selected layouts: {selectedLayouts.join(', ')}
)}
{/* Quick Timeframe Actions */}
{timeframes.map(tf => ( ))}
{/* Analyze Button */}
{/* Results Section */} {error && (
โš ๏ธ

Analysis Error

{error}

)} {loading && (

AI Processing

Analyzing {symbol} on {selectedTimeframes.length === 1 ? `${timeframes.find(tf => tf.value === selectedTimeframes[0])?.label} timeframe` : `${selectedTimeframes.length} timeframes` }...

)} {result && result.type === 'multi_timeframe' && (

๐Ÿ“Š Multi-Timeframe Analysis

{result.symbol} โ€ข {result.results.length} timeframes

Analysis Summary

{result.summary}

{result.results.map((timeframeResult: any, index: number) => (
{timeframeResult.success ? 'โœ…' : 'โŒ'} {timeframeResult.timeframeLabel} Timeframe
{timeframeResult.success ? 'Analysis Complete' : 'Failed'}
{timeframeResult.success && timeframeResult.result.analysis && (
Sentiment
{safeRender(timeframeResult.result.analysis.marketSentiment)}
Recommendation
{safeRender(timeframeResult.result.analysis.recommendation)}
Confidence
{safeRender(timeframeResult.result.analysis.confidence)}%
)} {timeframeResult.success && timeframeResult.result.analysis?.entry && (
Entry Setup
๐Ÿ“ ${safeRender(timeframeResult.result.analysis.entry.price)} {timeframeResult.result.analysis.entry.buffer && ( {safeRender(timeframeResult.result.analysis.entry.buffer)} )}
{timeframeResult.result.analysis.stopLoss && (
๐Ÿ›‘ SL: ${safeRender(timeframeResult.result.analysis.stopLoss.price)}
)}
)} {!timeframeResult.success && (
Analysis failed for this timeframe
)}
))}
)} {result && result.analysis && (

โœ… Analysis Complete

{result.screenshots && (
Screenshots: {result.screenshots.length} captured
)}
{/* Summary */}

Market Summary

{safeRender(result.analysis.summary)}

{/* Key Metrics */}

Market Sentiment

{safeRender(result.analysis.marketSentiment)}

Recommendation

{safeRender(result.analysis.recommendation)}

{result.analysis.confidence && (

{safeRender(result.analysis.confidence)}% confidence

)}
{/* Trading Levels */} {result.analysis.keyLevels && (

Resistance Levels

{result.analysis.keyLevels.resistance?.join(', ') || 'None identified'}

Support Levels

{result.analysis.keyLevels.support?.join(', ') || 'None identified'}

)} {/* Trading Setup */} {(result.analysis.entry || result.analysis.stopLoss || result.analysis.takeProfits) && (

Trading Setup

{result.analysis.entry && (
Entry Point

๐Ÿ“ ${safeRender(result.analysis.entry.price || result.analysis.entry)} {result.analysis.entry.buffer && ( {safeRender(result.analysis.entry.buffer)} )}

{result.analysis.entry.rationale && (

๐Ÿ’ก {safeRender(result.analysis.entry.rationale)}

)}
)} {result.analysis.stopLoss && (
Stop Loss

๐Ÿ›‘ ${safeRender(result.analysis.stopLoss.price || result.analysis.stopLoss)}

{result.analysis.stopLoss.rationale && (

๐Ÿ’ก {safeRender(result.analysis.stopLoss.rationale)}

)}
)} {result.analysis.takeProfits && (
Take Profit Targets
{result.analysis.takeProfits.tp1 && (
๐Ÿฅ‰ TP1: ${typeof result.analysis.takeProfits.tp1.price !== 'undefined' ? result.analysis.takeProfits.tp1.price : safeRender(result.analysis.takeProfits.tp1)}
{result.analysis.takeProfits.tp1.description && (

๐Ÿ“‹ {safeRender(result.analysis.takeProfits.tp1.description)}

)} {result.analysis.takeProfits.tp1.rsiExpectation && (

๐Ÿ“Š RSI: {safeRender(result.analysis.takeProfits.tp1.rsiExpectation)}

)} {result.analysis.takeProfits.tp1.obvExpectation && (

๐Ÿ“ˆ OBV: {safeRender(result.analysis.takeProfits.tp1.obvExpectation)}

)}
)} {result.analysis.takeProfits.tp2 && (
๐Ÿฅˆ TP2: ${typeof result.analysis.takeProfits.tp2.price !== 'undefined' ? result.analysis.takeProfits.tp2.price : safeRender(result.analysis.takeProfits.tp2)}
{result.analysis.takeProfits.tp2.description && (

๐Ÿ“‹ {safeRender(result.analysis.takeProfits.tp2.description)}

)} {result.analysis.takeProfits.tp2.rsiExpectation && (

๐Ÿ“Š RSI: {safeRender(result.analysis.takeProfits.tp2.rsiExpectation)}

)} {result.analysis.takeProfits.tp2.obvExpectation && (

๐Ÿ“ˆ OBV: {safeRender(result.analysis.takeProfits.tp2.obvExpectation)}

)}
)} {/* Fallback for simple take profit format */} {!result.analysis.takeProfits.tp1 && !result.analysis.takeProfits.tp2 && (

{typeof result.analysis.takeProfits === 'object' ? Object.values(result.analysis.takeProfits).map(tp => `$${safeRender(tp)}`).join(', ') : `$${safeRender(result.analysis.takeProfits)}`}

)}
)}
)} {/* Risk Management & Confirmation */} {(result.analysis.riskToReward || result.analysis.confirmationTrigger) && (

Risk Management

{result.analysis.riskToReward && (
Risk/Reward Ratio

โš–๏ธ {safeRender(result.analysis.riskToReward)}

)} {result.analysis.confirmationTrigger && (
Confirmation Trigger

๐Ÿ”” {safeRender(result.analysis.confirmationTrigger)}

)}
)} {/* Timeframe Risk Assessment */} {result.analysis.timeframeRisk && (

โฐ Timeframe Risk Assessment

{result.analysis.timeframeRisk.assessment && (
Risk Level

๐Ÿ“Š {safeRender(result.analysis.timeframeRisk.assessment)}

)} {result.analysis.timeframeRisk.positionSize && (
Position Size

๐Ÿ’ผ {safeRender(result.analysis.timeframeRisk.positionSize)}

)} {result.analysis.timeframeRisk.leverageRecommendation && (
Leverage

๐ŸŽš๏ธ {safeRender(result.analysis.timeframeRisk.leverageRecommendation)}

)}
)} {/* Technical Indicators */} {result.analysis.indicatorAnalysis && (

๐Ÿ“ˆ Technical Indicators

{result.analysis.indicatorAnalysis.rsi && (
๐Ÿ“Š RSI

{safeRender(result.analysis.indicatorAnalysis.rsi)}

)} {result.analysis.indicatorAnalysis.vwap && (
๐Ÿ“ˆ VWAP

{safeRender(result.analysis.indicatorAnalysis.vwap)}

)} {result.analysis.indicatorAnalysis.obv && (
๐Ÿ“Š OBV

{safeRender(result.analysis.indicatorAnalysis.obv)}

)} {result.analysis.indicatorAnalysis.macd && (
๐Ÿ“‰ MACD

{safeRender(result.analysis.indicatorAnalysis.macd)}

)}
)} {/* Alternatives */} {result.analysis.alternatives && (

๐Ÿ”„ Alternative Strategies

{result.analysis.alternatives.tigherStopOption && (
๐ŸŽฏ Tighter Stop Option

{safeRender(result.analysis.alternatives.tigherStopOption)}

)} {result.analysis.alternatives.scaledEntry && (
๐Ÿ“Š Scaled Entry

{safeRender(result.analysis.alternatives.scaledEntry)}

)} {result.analysis.alternatives.invalidationScenario && (
โŒ Invalidation Scenario

{safeRender(result.analysis.alternatives.invalidationScenario)}

)}
)} {/* Layout Comparison Section */} {result.analysis.layoutComparison && (

Multi-Layout Analysis

{result.analysis.layoutComparison.aiLayout && (
AI Layout Insights

{result.analysis.layoutComparison.aiLayout}

)} {result.analysis.layoutComparison.diyLayout && (
DIY Layout Insights

{result.analysis.layoutComparison.diyLayout}

)}
{result.analysis.layoutComparison.consensus && (
Layout Consensus

{result.analysis.layoutComparison.consensus}

)} {result.analysis.layoutComparison.divergences && (
Layout Divergences

{result.analysis.layoutComparison.divergences}

)}
)} {/* Enhanced Indicator Analysis */} {result.analysis.indicatorAnalysis?.crossLayoutConsensus && (

Cross-Layout Consensus

{result.analysis.indicatorAnalysis.crossLayoutConsensus}

)}
)} {result && !result.analysis && result.screenshots && (

Screenshots Captured

Screenshots were captured successfully, but AI analysis failed or was not requested.

Screenshots: {result.screenshots.length} captured
{result.screenshots.map((screenshot: string, index: number) => (
{screenshot.split('/').pop()}
))}
)}
) }