/**
 * ChartAnalysis - Tools for analyzing chart patterns and data
 *
 * Features:
 * - Pattern Detection: Hover over candles to detect candlestick patterns
 */
class ChartAnalysis {
    constructor() {
        this.isDetectionMode = false;
        this.cursorElement = null;
        this.resultsPopup = null;
        this.cursorRadius = 40; // pixels
        this.chartContainer = null;
        this.chart = null;
        this.candleSeries = null;

        // Bind methods
        this._onMouseMove = this._onMouseMove.bind(this);
        this._onMouseClick = this._onMouseClick.bind(this);
        this._onKeyDown = this._onKeyDown.bind(this);
        this._closeDropdownOnClickOutside = this._closeDropdownOnClickOutside.bind(this);
    }

    /**
     * Initialize with chart references
     */
    initialize(chartContainerId, chart, candleSeries) {
        this.chartContainer = document.getElementById(chartContainerId);
        this.chart = chart;
        this.candleSeries = candleSeries;
        this._createCursorElement();
        this._createResultsPopup();

        // Close dropdown when clicking outside
        document.addEventListener('click', this._closeDropdownOnClickOutside);
    }

    /**
     * Toggle the analyze dropdown
     */
    toggleDropdown() {
        const dropdown = document.getElementById('analyze_dropdown');
        if (dropdown) {
            const isVisible = dropdown.style.display !== 'none';
            dropdown.style.display = isVisible ? 'none' : 'block';
        }
    }

    _closeDropdownOnClickOutside(e) {
        const container = document.getElementById('analyze_charts_container');
        const dropdown = document.getElementById('analyze_dropdown');
        if (container && dropdown && !container.contains(e.target)) {
            dropdown.style.display = 'none';
        }
    }

    /**
     * Create the circular cursor element
     */
    _createCursorElement() {
        if (this.cursorElement) return;

        this.cursorElement = document.createElement('div');
        this.cursorElement.id = 'pattern_detection_cursor';
        this.cursorElement.style.width = (this.cursorRadius * 2) + 'px';
        this.cursorElement.style.height = (this.cursorRadius * 2) + 'px';
        document.body.appendChild(this.cursorElement);
    }

    /**
     * Create the results popup element
     */
    _createResultsPopup() {
        if (this.resultsPopup) return;

        this.resultsPopup = document.createElement('div');
        this.resultsPopup.id = 'pattern_results_popup';
        this.resultsPopup.innerHTML = `
            <div class="popup-header">
                <h4>Detected Patterns</h4>
                <button class="popup-close-btn" onclick="UI.chartAnalysis.stopPatternDetection()">&times;</button>
            </div>
            <div id="pattern_results_list"></div>
            <div class="popup-footer">Press ESC to exit</div>
        `;
        document.body.appendChild(this.resultsPopup);
    }

    /**
     * Start pattern detection mode
     */
    startPatternDetection() {
        // Close dropdown
        const dropdown = document.getElementById('analyze_dropdown');
        if (dropdown) dropdown.style.display = 'none';

        if (!this.chartContainer) {
            console.error('ChartAnalysis: Chart container not initialized');
            return;
        }

        this.isDetectionMode = true;

        // Show cursor
        if (this.cursorElement) {
            this.cursorElement.style.display = 'block';
        }

        // Change chart cursor
        this.chartContainer.style.cursor = 'none';

        // Add event listeners
        this.chartContainer.addEventListener('mousemove', this._onMouseMove);
        this.chartContainer.addEventListener('click', this._onMouseClick);
        document.addEventListener('keydown', this._onKeyDown);

        console.log('Pattern detection mode activated. Click on candles to detect patterns. Press ESC to exit.');
    }

    /**
     * Stop pattern detection mode
     */
    stopPatternDetection() {
        this.isDetectionMode = false;

        // Hide cursor
        if (this.cursorElement) {
            this.cursorElement.style.display = 'none';
        }

        // Hide results popup
        if (this.resultsPopup) {
            this.resultsPopup.style.display = 'none';
        }

        // Restore chart cursor
        if (this.chartContainer) {
            this.chartContainer.style.cursor = 'crosshair';
            this.chartContainer.removeEventListener('mousemove', this._onMouseMove);
            this.chartContainer.removeEventListener('click', this._onMouseClick);
        }
        document.removeEventListener('keydown', this._onKeyDown);

        console.log('Pattern detection mode deactivated.');
    }

    /**
     * Handle mouse movement - update cursor position
     */
    _onMouseMove(e) {
        if (!this.isDetectionMode || !this.cursorElement) return;

        const x = e.clientX - this.cursorRadius;
        const y = e.clientY - this.cursorRadius;

        this.cursorElement.style.left = x + 'px';
        this.cursorElement.style.top = y + 'px';
    }

    /**
     * Handle click - detect patterns at this location
     */
    async _onMouseClick(e) {
        if (!this.isDetectionMode) return;

        // Get chart container bounds
        const rect = this.chartContainer.getBoundingClientRect();
        const localX = e.clientX - rect.left;

        // Get time range covered by cursor
        const timeScale = this.chart.timeScale();
        const leftX = localX - this.cursorRadius;
        const rightX = localX + this.cursorRadius;

        const leftTime = timeScale.coordinateToTime(leftX);
        const rightTime = timeScale.coordinateToTime(rightX);

        if (!leftTime || !rightTime) {
            console.log('Could not determine time range');
            return;
        }

        // Show loading state
        this._showResults([{name: 'Analyzing...', value: 0}], e.clientX, e.clientY);

        // Request pattern detection from backend
        try {
            const patterns = await this._detectPatterns(leftTime, rightTime);
            this._showResults(patterns, e.clientX, e.clientY);
        } catch (error) {
            console.error('Pattern detection failed:', error);
            this._showResults([{name: 'Error detecting patterns', value: 0}], e.clientX, e.clientY);
        }
    }

    /**
     * Handle keyboard events
     */
    _onKeyDown(e) {
        if (e.key === 'Escape' && this.isDetectionMode) {
            this.stopPatternDetection();
        }
    }

    /**
     * Call backend to detect patterns in time range
     */
    async _detectPatterns(startTime, endTime) {
        const response = await fetch('/api/detect_patterns', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                user_name: window.UI.data.user_name,
                exchange: window.UI.data.exchange,
                symbol: window.UI.data.trading_pair,
                timeframe: window.UI.data.interval,
                start_time: startTime,
                end_time: endTime
            })
        });

        if (!response.ok) {
            throw new Error('Pattern detection request failed');
        }

        const data = await response.json();
        return data.patterns || [];
    }

    /**
     * Show results popup
     */
    _showResults(patterns, x, y) {
        if (!this.resultsPopup) return;

        const resultsList = document.getElementById('pattern_results_list');
        if (!resultsList) return;

        if (patterns.length === 0) {
            resultsList.innerHTML = '<div class="pattern-result-item">No patterns detected</div>';
        } else {
            resultsList.innerHTML = patterns.map(p => {
                const isBullish = p.value > 0;
                const className = p.value === 0 ? '' : (isBullish ? 'bullish' : 'bearish');
                const arrow = p.value === 0 ? '' : (isBullish ? '↑' : '↓');
                const strength = Math.abs(p.value);

                return `
                    <div class="pattern-result-item ${className}">
                        <span>${p.name} ${arrow}</span>
                        ${strength > 0 ? `<span class="pattern-strength">${strength}</span>` : ''}
                    </div>
                `;
            }).join('');
        }

        // Position popup near click but ensure it stays on screen
        const popupWidth = 250;
        const popupHeight = 200;
        let popupX = x + 20;
        let popupY = y - 50;

        if (popupX + popupWidth > window.innerWidth) {
            popupX = x - popupWidth - 20;
        }
        if (popupY + popupHeight > window.innerHeight) {
            popupY = window.innerHeight - popupHeight - 10;
        }
        if (popupY < 10) popupY = 10;

        this.resultsPopup.style.left = popupX + 'px';
        this.resultsPopup.style.top = popupY + 'px';
        this.resultsPopup.style.display = 'block';
    }
}

// Export for use
window.ChartAnalysis = ChartAnalysis;
