/**
 * ChessVIP Bridge Extension v4.9
 * 
 * This extension is INTENTIONALLY minimal.
 * It does NOT contain any engine or license logic.
 * All analysis is done by ChessVIP Engine (desktop app).
 * 
 * Flow: Read FEN → Background proxy → localhost:9876 → Receive bestmove → Draw arrows
 */

(function() {
    'use strict';

    const POLL_INTERVAL = 800;
    
    let lastFen = '';
    let engineConnected = false;
    let isAnalyzing = false;
    let panel = null;

    // ─── ENGINE COMMUNICATION (via background proxy) ───
    function engineRequest(endpoint, method, body) {
        return new Promise((resolve) => {
            chrome.runtime.sendMessage(
                { type: 'ENGINE_REQUEST', endpoint, method: method || 'GET', body },
                (response) => {
                    if (chrome.runtime.lastError || !response || !response.success) {
                        resolve(null);
                    } else {
                        resolve(response.data);
                    }
                }
            );
        });
    }

    // ─── FEN EXTRACTION ────────────────────────────────
    function extractFEN() {
        try {
            const pieces = document.querySelectorAll('.piece');
            if (!pieces.length) return null;

            const board = Array(8).fill(null).map(() => Array(8).fill(''));
            
            pieces.forEach(piece => {
                const classes = piece.className.split(' ');
                let pieceType = '', square = '';
                
                classes.forEach(cls => {
                    if (cls.length === 2 && 'wb'.includes(cls[0]) && 'prnbqk'.includes(cls[1])) {
                        pieceType = cls;
                    }
                    if (cls.startsWith('square-') && cls.length >= 9) {
                        square = cls.replace('square-', '');
                    }
                });

                if (pieceType && square && square.length >= 2) {
                    const col = parseInt(square[0]) - 1;
                    const row = parseInt(square[1]) - 1;
                    if (col >= 0 && col < 8 && row >= 0 && row < 8) {
                        const pieceMap = {
                            'wp': 'P', 'wn': 'N', 'wb': 'B', 'wr': 'R', 'wq': 'Q', 'wk': 'K',
                            'bp': 'p', 'bn': 'n', 'bb': 'b', 'br': 'r', 'bq': 'q', 'bk': 'k'
                        };
                        board[7 - row][col] = pieceMap[pieceType] || '';
                    }
                }
            });

            let fen = '';
            for (let row = 0; row < 8; row++) {
                let empty = 0;
                for (let col = 0; col < 8; col++) {
                    if (board[row][col] === '') {
                        empty++;
                    } else {
                        if (empty > 0) { fen += empty; empty = 0; }
                        fen += board[row][col];
                    }
                }
                if (empty > 0) fen += empty;
                if (row < 7) fen += '/';
            }
            
            const turn = detectTurn();
            fen += ` ${turn} KQkq - 0 1`;
            
            return fen;
        } catch (e) {
            return null;
        }
    }

    function detectTurn() {
        const clocks = document.querySelectorAll('.clock-component');
        for (const clock of clocks) {
            if (clock.classList.contains('clock-player-turn')) {
                const isBottom = clock.closest('.board-layout-bottom') !== null;
                const boardFlipped = document.querySelector('.board.flipped') !== null;
                if (isBottom !== boardFlipped) return 'w';
                return 'b';
            }
        }
        return 'w';
    }

    // ─── ENGINE STATUS & ANALYSIS ──────────────────────
    async function checkEngineStatus() {
        const data = await engineRequest('/status');
        engineConnected = !!data;
        return data;
    }

    async function requestAnalysis(fen) {
        if (!engineConnected || isAnalyzing) return null;
        
        isAnalyzing = true;
        const data = await engineRequest('/analyze', 'POST', { fen, depth: 18 });
        isAnalyzing = false;
        
        if (!data) return null;
        
        if (data.error === 'LICENSE_REQUIRED' || data.error === 'LICENSE_EXPIRED') {
            updatePanel('license-needed', data);
            return null;
        }
        
        return data;
    }

    // ─── ARROW DRAWING ─────────────────────────────────
    function drawArrow(move) {
        clearArrows();
        
        if (!move || move.length < 4) return;
        
        const from = move.substring(0, 2);
        const to = move.substring(2, 4);
        
        const board = document.querySelector('.board');
        if (!board) return;
        
        const boardRect = board.getBoundingClientRect();
        const squareSize = boardRect.width / 8;
        const flipped = board.classList.contains('flipped');
        
        function squareToCoords(sq) {
            let col = sq.charCodeAt(0) - 97;
            let row = parseInt(sq[1]) - 1;
            if (flipped) { col = 7 - col; row = 7 - row; }
            else { row = 7 - row; }
            return {
                x: (col + 0.5) * squareSize,
                y: (row + 0.5) * squareSize
            };
        }
        
        const fromCoords = squareToCoords(from);
        const toCoords = squareToCoords(to);
        
        const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.setAttribute('class', 'cvp-arrow-layer');
        svg.style.cssText = `position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:100;`;
        
        const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
        const marker = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
        marker.setAttribute('id', 'cvp-arrowhead');
        marker.setAttribute('markerWidth', '10');
        marker.setAttribute('markerHeight', '7');
        marker.setAttribute('refX', '10');
        marker.setAttribute('refY', '3.5');
        marker.setAttribute('orient', 'auto');
        const polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
        polygon.setAttribute('points', '0 0, 10 3.5, 0 7');
        polygon.setAttribute('fill', '#00ff88');
        marker.appendChild(polygon);
        defs.appendChild(marker);
        svg.appendChild(defs);
        
        const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
        line.setAttribute('x1', fromCoords.x);
        line.setAttribute('y1', fromCoords.y);
        line.setAttribute('x2', toCoords.x);
        line.setAttribute('y2', toCoords.y);
        line.setAttribute('stroke', '#00ff88');
        line.setAttribute('stroke-width', squareSize * 0.15);
        line.setAttribute('stroke-opacity', '0.8');
        line.setAttribute('marker-end', 'url(#cvp-arrowhead)');
        svg.appendChild(line);
        
        [from, to].forEach((sq, i) => {
            const coords = i === 0 ? fromCoords : toCoords;
            const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
            rect.setAttribute('x', coords.x - squareSize/2);
            rect.setAttribute('y', coords.y - squareSize/2);
            rect.setAttribute('width', squareSize);
            rect.setAttribute('height', squareSize);
            rect.setAttribute('fill', i === 0 ? '#00ff8833' : '#00ff8855');
            rect.setAttribute('class', 'cvp-highlight');
            svg.appendChild(rect);
        });
        
        board.style.position = 'relative';
        board.appendChild(svg);
    }

    function clearArrows() {
        document.querySelectorAll('.cvp-arrow-layer').forEach(el => el.remove());
    }

    // ─── STATUS PANEL ──────────────────────────────────
    function createPanel() {
        if (panel) return;
        
        panel = document.createElement('div');
        panel.id = 'cvp-engine-panel';
        panel.innerHTML = `
            <div class="cvp-engine-header">
                <span class="cvp-engine-logo">\u265A ChessVIP</span>
                <span class="cvp-engine-version">v4.9</span>
                <button class="cvp-engine-close" title="Close">\u00D7</button>
            </div>
            <div class="cvp-engine-status">
                <div class="cvp-status-dot"></div>
                <span class="cvp-status-text">Connecting to engine...</span>
            </div>
            <div class="cvp-engine-info"></div>
        `;
        
        document.body.appendChild(panel);
        
        panel.querySelector('.cvp-engine-close').addEventListener('click', () => {
            panel.style.display = 'none';
        });
    }

    function updatePanel(status, data = {}) {
        if (!panel) createPanel();
        
        const dot = panel.querySelector('.cvp-status-dot');
        const text = panel.querySelector('.cvp-status-text');
        const info = panel.querySelector('.cvp-engine-info');
        
        switch(status) {
            case 'connected':
                dot.className = 'cvp-status-dot connected';
                text.textContent = `Engine: ${data.engine || 'ready'}`;
                info.textContent = data.licensed ? 
                    `Licensed (${data.plan})` : 
                    'Activate license in Engine app';
                break;
            case 'disconnected':
                dot.className = 'cvp-status-dot disconnected';
                text.textContent = 'Engine not running';
                info.textContent = 'Start ChessVIP Engine app';
                break;
            case 'analyzing':
                dot.className = 'cvp-status-dot analyzing';
                text.textContent = `Analyzing... depth ${data.depth || '?'}`;
                info.textContent = data.bestmove ? `Best: ${data.bestmove}` : '';
                break;
            case 'result':
                dot.className = 'cvp-status-dot connected';
                text.textContent = `Best: ${data.bestmove} (depth ${data.depth})`;
                info.textContent = `Source: ${data.source || 'engine'}`;
                break;
            case 'license-needed':
                dot.className = 'cvp-status-dot warning';
                text.textContent = 'License required';
                info.textContent = 'Activate in ChessVIP Engine app';
                break;
        }
    }

    // ─── MAIN LOOP ─────────────────────────────────────
    async function mainLoop() {
        const status = await checkEngineStatus();
        
        if (!status) {
            updatePanel('disconnected');
            setTimeout(mainLoop, 3000);
            return;
        }
        
        updatePanel('connected', status);
        
        if (!status.licensed) {
            setTimeout(mainLoop, 5000);
            return;
        }
        
        const fen = extractFEN();
        
        if (fen && fen !== lastFen) {
            lastFen = fen;
            updatePanel('analyzing', {});
            
            const result = await requestAnalysis(fen);
            
            if (result && result.bestmove) {
                drawArrow(result.bestmove);
                updatePanel('result', result);
            }
        }
        
        setTimeout(mainLoop, POLL_INTERVAL);
    }

    // ─── INIT ──────────────────────────────────────────
    function init() {
        if (!document.querySelector('.board')) {
            setTimeout(init, 1000);
            return;
        }
        
        createPanel();
        console.log('[ChessVIP Bridge] v4.9 loaded, connecting via background proxy...');
        mainLoop();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        setTimeout(init, 500);
    }
})();
