// Optimized Market Reversal Detection Methods
// Shows only the most significant reversal points in visible zone

SmoothTradingChart.prototype.detectMarketReversals = function () {
    if (this.candleData.length < 20) return;

    const visibleCandles = this.getVisibleCandles();
    if (visibleCandles.length < 10) return;

    // Find the highest and lowest points in visible zone
    const significantReversals = this.findSignificantReversals(visibleCandles);

    // Update reversal boxes with only significant points
    this.updateReversalBoxes(significantReversals);
};

SmoothTradingChart.prototype.findSignificantReversals = function (visibleCandles) {
    const reversals = [];

    if (visibleCandles.length === 0) return reversals;

    // Find highest and lowest points in visible zone
    let highestCandle = null;
    let lowestCandle = null;
    let highestPrice = -Infinity;
    let lowestPrice = Infinity;

    visibleCandles.forEach(candle => {
        const candleIndex = this.candleData.indexOf(candle);
        if (candleIndex === -1) return;

        // Skip only future candles (allow current running candle)
        if (candleIndex > this.currentCandleIndex) return;

        // For running candle, use real-time high/low values from currentPrice
        let candleHigh = candle.high;
        let candleLow = candle.low;
        
        if (candleIndex === this.currentCandleIndex) {
            candleHigh = Math.max(candle.open, this.currentPrice, this.runningHigh ?? candle.open);
            candleLow = Math.min(candle.open, this.currentPrice, this.runningLow ?? candle.open);
        }

        if (candleHigh > highestPrice) {
            highestPrice = candleHigh;
            highestCandle = { candleIndex, price: candleHigh, type: 'top' };
        }

        if (candleLow < lowestPrice) {
            lowestPrice = candleLow;
            lowestCandle = { candleIndex, price: candleLow, type: 'bottom' };
        }
    });

    if (highestCandle) reversals.push(highestCandle);
    if (lowestCandle && lowestCandle.candleIndex !== highestCandle?.candleIndex) {
        reversals.push(lowestCandle);
    }

    return reversals;
};

SmoothTradingChart.prototype.isTopReversal = function (candleIndex) {
    if (candleIndex < 4 || candleIndex >= this.candleData.length - 4) return false;

    const candle = this.candleData[candleIndex];
    const prev1 = this.candleData[candleIndex - 1];
    const prev2 = this.candleData[candleIndex - 2];
    const prev3 = this.candleData[candleIndex - 3];
    const prev4 = this.candleData[candleIndex - 4];
    const next1 = this.candleData[candleIndex + 1];
    const next2 = this.candleData[candleIndex + 2];
    const next3 = this.candleData[candleIndex + 3];
    const next4 = this.candleData[candleIndex + 4];

    if (!candle || !prev1 || !prev2 || !prev3 || !prev4 || !next1 || !next2 || !next3 || !next4) return false;

    return candle.high > prev1.high && candle.high > prev2.high && candle.high > prev3.high && candle.high > prev4.high &&
        candle.high > next1.high && candle.high > next2.high && candle.high > next3.high && candle.high > next4.high;
};

SmoothTradingChart.prototype.isBottomReversal = function (candleIndex) {
    if (candleIndex < 4 || candleIndex >= this.candleData.length - 4) return false;

    const candle = this.candleData[candleIndex];
    const prev1 = this.candleData[candleIndex - 1];
    const prev2 = this.candleData[candleIndex - 2];
    const prev3 = this.candleData[candleIndex - 3];
    const prev4 = this.candleData[candleIndex - 4];
    const next1 = this.candleData[candleIndex + 1];
    const next2 = this.candleData[candleIndex + 2];
    const next3 = this.candleData[candleIndex + 3];
    const next4 = this.candleData[candleIndex + 4];

    if (!candle || !prev1 || !prev2 || !prev3 || !prev4 || !next1 || !next2 || !next3 || !next4) return false;

    return candle.low < prev1.low && candle.low < prev2.low && candle.low < prev3.low && candle.low < prev4.low &&
        candle.low < next1.low && candle.low < next2.low && candle.low < next3.low && candle.low < next4.low;
};

SmoothTradingChart.prototype.calculateReversalStrength = function (candleIndex, type) {
    // Calculate strength based on price difference from surrounding candles
    const candle = this.candleData[candleIndex];
    const surroundingCandles = this.candleData.slice(Math.max(0, candleIndex - 8), candleIndex + 9);

    if (type === 'top') {
        const avgHigh = surroundingCandles.reduce((sum, c) => sum + c.high, 0) / surroundingCandles.length;
        return (candle.high - avgHigh) / avgHigh;
    } else {
        const avgLow = surroundingCandles.reduce((sum, c) => sum + c.low, 0) / surroundingCandles.length;
        return (avgLow - candle.low) / avgLow;
    }
};

SmoothTradingChart.prototype.updateReversalBoxes = function (significantReversals) {
    // Clear all existing boxes and only show current significant reversals
    this.reversalBoxes = significantReversals.map(reversal => ({
        candleIndex: reversal.candleIndex,
        price: reversal.price,
        type: reversal.type,
        confirmed: true,
        strength: reversal.strength
    }));
};

SmoothTradingChart.prototype.drawReversalBoxes = function () {
    if (!this.reversalBoxes.length) return;

    const a = this.getChartArea();
    const twoCm = 100;
    const startX = a.left + this.panOffset + twoCm;

    // Reset hover state
    this.isHoveringReversalBox = false;

    this.reversalBoxes.forEach(box => {
        const isOddCandle = (box.candleIndex % 2) === 0;
        const gridIndex = Math.floor(box.candleIndex / 2);
        const candleX = isOddCandle ?
            startX + gridIndex * twoCm :
            startX + gridIndex * twoCm + twoCm / 2;

        const priceY = this.priceToY(box.price);

        // Position box so right edge aligns with candle's wick (center position)
        const boxWidth = 55;
        const boxLeft = candleX - boxWidth; // Right edge of box aligns with candle's wick

        // Position box 3 pixels away from high/low point
        const boxY = box.type === 'top' ? priceY - 3 - 25 : priceY + 3;

        // Only show box if candle center is visible (respects 50px clipping boundary)
        if (candleX < 50 || candleX > this.canvas.width) return;

        const clippedLeft = Math.max(boxLeft, 50);
        const clippedWidth = Math.min(boxLeft + boxWidth, this.canvas.width) - clippedLeft;

        if (clippedWidth <= 0) return;

        // Check if mouse is hovering over this box
        const isHovered = this.mouseX >= clippedLeft && this.mouseX <= clippedLeft + clippedWidth &&
            this.mouseY >= boxY && this.mouseY <= boxY + 25;

        // Set colors based on hover state
        this.ctx.fillStyle = isHovered ? 'rgba(73, 79, 101, 0.8)' : 'rgba(42, 46, 62, 0.8)';

        // Set cursor and hover state
        if (isHovered) {
            this.isHoveringReversalBox = true;
            this.canvas.style.cursor = 'pointer';
        }

        // Apply universal clipping for this box and its text
        this.ctx.save();
        this.ctx.beginPath();
        this.ctx.rect(50, 0, this.canvas.width - 50, this.canvas.height);
        this.ctx.clip();

        // Draw rectangle with cut corners using full width (clipping handles the edges)
        this.ctx.beginPath();
        const cut = 4;
        const x = boxLeft;
        const y = boxY;
        const width = boxWidth;
        const height = 25;

        if (box.type === 'top') {
            // Top reversal: cut corners on top-left, top-right, bottom-left (sharp bottom-right)
            this.ctx.moveTo(x + cut, y);
            this.ctx.lineTo(x + width - cut, y);
            this.ctx.lineTo(x + width, y + cut);
            this.ctx.lineTo(x + width, y + height);
            this.ctx.lineTo(x + cut, y + height);
            this.ctx.lineTo(x, y + height - cut);
            this.ctx.lineTo(x, y + cut);
            this.ctx.lineTo(x + cut, y);
        } else {
            // Bottom reversal: cut corners on top-left, bottom-left, bottom-right (sharp top-right)
            this.ctx.moveTo(x + cut, y);
            this.ctx.lineTo(x + width, y);
            this.ctx.lineTo(x + width, y + height - cut);
            this.ctx.lineTo(x + width - cut, y + height);
            this.ctx.lineTo(x + cut, y + height);
            this.ctx.lineTo(x, y + height - cut);
            this.ctx.lineTo(x, y + cut);
            this.ctx.lineTo(x + cut, y);
        }

        this.ctx.closePath();
        this.ctx.fill();

        this.ctx.fillStyle = isHovered ? '#F2F2F4' : '#616370';
        this.ctx.font = '600 10px Arial';
        this.ctx.textAlign = 'center';

        // Display exact reversal price with asset-specific decimal points
        const textX = boxLeft + boxWidth / 2;
        const formattedPrice = this.formatPrice ? this.formatPrice(box.price) : box.price.toFixed(5);
        this.ctx.fillText(formattedPrice, textX, boxY + 16);

        this.ctx.restore();
    });
};