import { IPoint } from "@fullstackcraftllc/codevideo-types";
import { convertToContainerCoordinates } from "./convertToContainerCoordinates.js";
import { DEFAULT_MOUSE_POSITION } from "src/constants/CodeVideoIDEConstants.js";

export const getCoordinatesOfFileOrFolder = (fileOrFolderPath: string, containerRef: React.RefObject<HTMLDivElement | null>): IPoint => {
    if (!containerRef) return DEFAULT_MOUSE_POSITION;
    console.log('🎯 [getCoordinatesOfFileOrFolder] Looking for:', fileOrFolderPath);
    
    const selector = `[data-codevideo-id="file-explorer-${fileOrFolderPath}"]`;
    console.log('🔍 [getCoordinatesOfFileOrFolder] Selector:', selector);
    
    const fileElement = document.querySelector(selector);

    // TODO: happens quite a lot, need to rearrange when the file tree is ready to be found.
    if (!fileElement) {
        console.log('❌ [getCoordinatesOfFileOrFolder] Element not found');
        // Let's see what elements we do have
        const allFileExplorerElements = document.querySelectorAll('[data-codevideo-id^="file-explorer-"]');
        console.log('📋 [getCoordinatesOfFileOrFolder] Available file explorer elements:');
        allFileExplorerElements.forEach(el => {
            console.log(`  - ${el.getAttribute('data-codevideo-id')}`);
        });
        return DEFAULT_MOUSE_POSITION;
    }
    
    console.log('✅ [getCoordinatesOfFileOrFolder] Found element:', fileElement);
    const rect = fileElement.getBoundingClientRect();
    console.log('📐 [getCoordinatesOfFileOrFolder] Element rect:', {
        left: rect.left,
        top: rect.top,
        width: rect.width,
        height: rect.height,
        right: rect.right,
        bottom: rect.bottom
    });
    
    const absoluteCoords = {
        x: rect.left + rect.width / 2,
        y: rect.top + rect.height / 2
    };
    console.log('📍 [getCoordinatesOfFileOrFolder] Absolute center coords:', absoluteCoords);
    
    const result = convertToContainerCoordinates(absoluteCoords, containerRef);
    console.log('🎯 [getCoordinatesOfFileOrFolder] Final container-relative coords:', result);
    
    return result;
};