let complexNumbers = [];
let selectedComplexIndex = null;

function createComplexNumber() {
    const realPart = parseFloat(document.getElementById('real-part').value);
    const imaginaryPart = parseFloat(
        document.getElementById('imaginary-part').value
    );

    if (isNaN(realPart) || isNaN(imaginaryPart)) {
        alert(
            'Пожалуйста, введите корректные значения для действительной и мнимой частей.'
        );
        return;
    }

    const complex = new Complex(realPart, imaginaryPart);
    complexNumbers.push(complex);

    renderComplexNumbers();
    clearActionsLog();
}

function renderComplexNumbers() {
    const container = document.getElementById('complex-numbers');
    container.innerHTML = '';

    complexNumbers.forEach((complex, index) => {
        const complexDiv = document.createElement('div');
        complexDiv.className = 'complex-number';
        complexDiv.innerHTML = `
            <strong>Комплексное число ${
                index + 1
            }:</strong> ${complex.toString()}<br>
            <button onclick="setSelectedComplex(${index})">Выбрать</button>
        `;
        container.appendChild(complexDiv);
    });
}

function setSelectedComplex(index) {
    selectedComplexIndex = index;
    document.getElementById('selected-complex').textContent = `Выбрано число ${
        index + 1
    }: ${complexNumbers[index].toString()}`;
}

function performOperation(operation) {
    if (selectedComplexIndex === null) {
        alert('Пожалуйста, выберите комплексное число.');
        return;
    }

    const complex = complexNumbers[selectedComplexIndex];
    const realPart = parseFloat(document.getElementById('real-part-op').value);
    const imaginaryPart = parseFloat(
        document.getElementById('imaginary-part-op').value
    );
    const otherComplex = new Complex(realPart, imaginaryPart);

    if (isNaN(realPart) || isNaN(imaginaryPart)) {
        alert(
            'Пожалуйста, введите корректные значения для действительной и мнимной частей.'
        );
        return;
    }

    if (operation === 'add') {
        complex.add(otherComplex);
    } else if (operation === 'subtract') {
        complex.subtract(otherComplex);
    } else if (operation === 'multiply') {
        complex.multiply(otherComplex);
    } else if (operation === 'divide') {
        complex.divide(otherComplex);
    }

    renderComplexNumbers();
    clearActionsLog();
    logActions(complex);
}

function clearActionsLog() {
    const log = document.getElementById('actions-log');
    log.textContent = '';
}

function logActions(complex) {
    const log = document.getElementById('actions-log');
    complex.actions.forEach((action) => {
        log.textContent += complex.formatAction(action) + '\n';
    });
}

document.addEventListener('DOMContentLoaded', () => {
    renderComplexNumbers();
});
