﻿/* boarddraw.js */

/* --- 1. Board Generation --- */
function fenToBoard(fen) {
    const board = [];
    const fenRows = fen.split(' ')[0].split('/');
    for (let row of fenRows) {
        const boardRow = [];
        for (let char of row) {
            if (isNaN(char)) {
                boardRow.push(char);
            } else {
                for (let i = 0; i < parseInt(char); i++) {
                    boardRow.push('.');
                }
            }
        }
        board.push(boardRow);
    }
    return board;
}

function createCoordinateElement(content) {
    const coordinateElement = document.createElement('td');
    coordinateElement.className = 'coordinate';
    coordinateElement.textContent = content;
    return coordinateElement;
}

function generateChessboard(fen, boardId, squareSize = 36) {
    const container = document.getElementById(boardId);
    if (!container) return;
    container.innerHTML = '';

    // 1. Wrapper
    const wrapper = document.createElement('div');
    wrapper.className = 'board-wrapper';

    // 2. Table
    const table = document.createElement('table');
    table.className = 'chessboard-table';

    // 3. SVG Layer
    const svgLayer = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    svgLayer.className = 'arrow-layer';
    svgLayer.id = boardId + '_arrows';

    const board = fenToBoard(fen);
    
    // Update path to match your server if needed
    const pieceImages = {
        'P': '/gif/merida35/white_pawn.png', 'N': '/gif/merida35/white_knight.png',
        'B': '/gif/merida35/white_bishop.png', 'R': '/gif/merida35/white_rook.png',
        'Q': '/gif/merida35/white_queen.png', 'K': '/gif/merida35/white_king.png',
        'p': '/gif/merida35/black_pawn.png', 'n': '/gif/merida35/black_knight.png',
        'b': '/gif/merida35/black_bishop.png', 'r': '/gif/merida35/black_rook.png',
        'q': '/gif/merida35/black_queen.png', 'k': '/gif/merida35/black_king.png'
    };

    // --- Top Coords ---
    const fileLabelsTop = document.createElement('tr');
    const files = [' ', 'a','b','c','d','e','f','g','h',' '];
    for (let file of files) fileLabelsTop.appendChild(createCoordinateElement(file));
    table.appendChild(fileLabelsTop);

    // --- Board Rows ---
    for (let i = 0; i < 8; i++) {
        const row = document.createElement('tr');
        row.appendChild(createCoordinateElement(8 - i)); // Left Coord

        for (let j = 0; j < 8; j++) {
            const cell = document.createElement('td');
            // Explicitly set dimensions inline to force layout
            cell.style.width = squareSize + 'px';
            cell.style.height = squareSize + 'px';
            cell.className = (i + j) % 2 === 0 ? 'white' : 'black';
            
            // Add data identifier for arrow targeting
            const fileChar = String.fromCharCode(97 + j);
            const rankChar = (8 - i).toString();
            cell.setAttribute('data-coord', fileChar + rankChar);

            if (board[i][j] !== '.') {
                const img = document.createElement('img');
                img.src = pieceImages[board[i][j]];
                cell.appendChild(img);
            }
            row.appendChild(cell);
        }

        row.appendChild(createCoordinateElement(8 - i)); // Right Coord
        table.appendChild(row);
    }

    // --- Bottom Coords ---
    const fileLabelsBottom = document.createElement('tr');
    for (let file of files) fileLabelsBottom.appendChild(createCoordinateElement(file));
    table.appendChild(fileLabelsBottom);

    wrapper.appendChild(table);
    wrapper.appendChild(svgLayer);
    container.appendChild(wrapper);
}

/* --- 2. Arrow Logic (Using GetBoundingClientRect) --- */
function drawArrow(boardId, fromSquare, toSquare, color = '#e63946', opacity = 0.9) {
    const container = document.getElementById(boardId);
    if (!container) return;
    const svg = container.querySelector('.arrow-layer');
    const table = container.querySelector('table');
    if (!svg || !table) return;

    const fromCell = table.querySelector(`td[data-coord="${fromSquare}"]`);
    const toCell = table.querySelector(`td[data-coord="${toSquare}"]`);

    if (!fromCell || !toCell) return;

    // Use absolute screen positions to be safe
    const svgRect = svg.getBoundingClientRect();
    const fromRect = fromCell.getBoundingClientRect();
    const toRect = toCell.getBoundingClientRect();

    // Calculate center relative to the SVG canvas
    const startX = fromRect.left + fromRect.width / 2 - svgRect.left;
    const startY = fromRect.top + fromRect.height / 2 - svgRect.top;
    const endX = toRect.left + toRect.width / 2 - svgRect.left;
    const endY = toRect.top + toRect.height / 2 - svgRect.top;

    // Math for arrowhead
    const dx = endX - startX;
    const dy = endY - startY;
    const angle = Math.atan2(dy, dx);
    const hypotenuse = Math.sqrt(dx * dx + dy * dy);

    const squareSize = fromRect.width; 
    const headLength = squareSize * 0.55; 
    const headWidth = squareSize * 0.4;
    const lineWidth = squareSize * 0.15;
    
    // Shorten shaft so it doesn't poke through the head
    const shaftLength = hypotenuse - headLength + (lineWidth * 0.2); 
    const shaftEndX = startX + shaftLength * Math.cos(angle);
    const shaftEndY = startY + shaftLength * Math.sin(angle);

    const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
    g.setAttribute("opacity", opacity);

    // Shaft
    const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
    line.setAttribute("x1", startX);
    line.setAttribute("y1", startY);
    line.setAttribute("x2", shaftEndX);
    line.setAttribute("y2", shaftEndY);
    line.setAttribute("stroke", color);
    line.setAttribute("stroke-width", lineWidth);
    line.setAttribute("stroke-linecap", "butt");

    // Arrowhead (Triangle)
    const PI = Math.PI;
    const bx1 = shaftEndX + (headWidth/2) * Math.cos(angle + PI/2);
    const by1 = shaftEndY + (headWidth/2) * Math.sin(angle + PI/2);
    const bx2 = shaftEndX + (headWidth/2) * Math.cos(angle - PI/2);
    const by2 = shaftEndY + (headWidth/2) * Math.sin(angle - PI/2);

    const poly = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
    poly.setAttribute("points", `${endX},${endY} ${bx1},${by1} ${bx2},${by2}`);
    poly.setAttribute("fill", color);

    g.appendChild(line);
    g.appendChild(poly);
    svg.appendChild(g);
}

// Global Redraw Handler
window.addEventListener('resize', function() {
    document.querySelectorAll('.arrow-layer').forEach(svg => svg.innerHTML = '');
    if (typeof drawAllArrows === 'function') drawAllArrows();
});