"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const inspector_1 = require("./inspector");
const ui_1 = require("./ui");
let isSelectorModeActive = false;
let currentHoveredElement = null;
function handleMouseOver(e) {
    if (currentHoveredElement) {
        currentHoveredElement.classList.remove('repoburg-highlight');
    }
    currentHoveredElement = e.target;
    currentHoveredElement.classList.add('repoburg-highlight');
}
function handleMouseOut() {
    if (currentHoveredElement) {
        currentHoveredElement.classList.remove('repoburg-highlight');
        currentHoveredElement = null;
    }
}
function handleClick(e) {
    e.preventDefault();
    e.stopPropagation();
    toggleSelectorMode();
    if (!currentHoveredElement)
        return;
    const result = (0, inspector_1.getComponentTreeFromElement)(currentHoveredElement);
    if (result.error || !result.hierarchy) {
        (0, ui_1.showToast)(result.error || 'Unknown error', 'error');
    }
    else {
        (0, ui_1.showPromptModal)(result.hierarchy, window.location.href, submitPrompt);
    }
}
function toggleSelectorMode() {
    isSelectorModeActive = !isSelectorModeActive;
    const button = document.getElementById('repoburg-float-btn');
    if (isSelectorModeActive) {
        button.classList.add('active');
        button.textContent = 'Exit';
        document.addEventListener('mouseover', handleMouseOver);
        document.addEventListener('mouseout', handleMouseOut);
        document.addEventListener('click', handleClick, true);
    }
    else {
        button.classList.remove('active');
        button.textContent = 'Repo';
        if (currentHoveredElement) {
            currentHoveredElement.classList.remove('repoburg-highlight');
        }
        document.removeEventListener('mouseover', handleMouseOver);
        document.removeEventListener('mouseout', handleMouseOut);
        document.removeEventListener('click', handleClick, true);
    }
}
async function submitPrompt(prompt, hierarchy, url) {
    const backendPort = window.REPOBURG_BACKEND_PORT;
    if (!backendPort) {
        (0, ui_1.showToast)('Repoburg backend port not found.', 'error');
        return;
    }
    const hierarchyText = hierarchy
        .slice()
        .reverse()
        .map((component, index) => {
        const indent = '  '.repeat(index);
        const propsString = JSON.stringify(component.props);
        const stateString = component.state && Object.keys(component.state).length > 0
            ? `, state: ${JSON.stringify(component.state)}`
            : '';
        return `${indent}- ${component.name} (props: ${propsString}${stateString})`;
    })
        .join('\n');
    const explanationForAI = `This data structure is a React Component Tree, representing the hierarchy of components from the application's root down to the element the user selected. The indentation signifies the parent-child nesting relationship. Each line contains the component/element name, its 'props' (data passed down to it), and its 'state' (internal data it manages). As an AI agent, use this structural and data context to understand the application's architecture and the flow of information related to the user's request. The last element in the list is the user's direct target.`;
    const contextHeader = `--- Visual Inspector Context ---\nURL: ${url}\n\n${explanationForAI}\n\nComponent Hierarchy:\n${hierarchyText}\n\n--- User Prompt ---`;
    const fullPrompt = `${contextHeader}\n\n${prompt}`;
    const payload = {
        prompt: fullPrompt,
        componentPath: '',
        parentComponentPath: undefined,
    };
    try {
        const response = await fetch(`http://localhost:${backendPort}/visual-editor/submit`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload),
        });
        if (!response.ok) {
            const errorData = await response.json().catch(() => ({ message: 'Failed to submit prompt' }));
            throw new Error(errorData.message);
        }
        (0, ui_1.showToast)('Prompt submitted successfully!');
    }
    catch (error) {
        console.error('Repoburg Error:', error);
        (0, ui_1.showToast)(error instanceof Error ? error.message : String(error), 'error');
    }
}
function initialize() {
    if (document.getElementById('repoburg-float-btn'))
        return;
    console.log('Repoburg Visual Editor: Initializing UI.');
    console.log('Repoburg Backend Port:', window.REPOBURG_BACKEND_PORT || 'Not Set');
    (0, ui_1.injectStyles)();
    (0, ui_1.createToast)();
    (0, ui_1.createFloatingButton)(toggleSelectorMode);
}
initialize();
//# sourceMappingURL=main.js.map