// Materials Database JavaScript

let materialsData = [];
let currentMaterial = null;
let tempChart = null;

// Initialize on page load
$(document).ready(function() {
    loadMaterialsList();
    bindEvents();
});

function bindEvents() {
    // Search input
    $('#materialSearch').on('input', debounce(function() {
        filterMaterials($(this).val());
    }, 300));
    
    // Calculate alloy button
    $('#calculateAlloyBtn').click(function() {
        showAlloyCalculator();
    });
    
    // Compare button
    $('#compareBtn').click(function() {
        showComparison();
    });
    
    // Add custom material button
    $('#addCustomBtn').click(function() {
        const modal = new bootstrap.Modal($('#customMaterialModal')[0]);
        modal.show();
    });
    
    // Save custom material
    $('#saveCustomMaterialBtn').click(function() {
        saveCustomMaterial();
    });
    
    // Calculate alloy properties
    $('#calculateAlloyPropsBtn').click(function() {
        calculateAlloyProperties();
    });
    
    // Temperature calculation
    $('#calcTempBtn').click(function() {
        calculateTemperature();
    });
    
    // Temperature slider change
    $('#tempValue').on('input', function() {
        if (currentMaterial) {
            updateTemperaturePlot();
        }
    });
    
    // Compare materials
    $('#comparePropsBtn').click(function() {
        compareMaterials();
    });
}

// Load materials list
function loadMaterialsList() {
    $.ajax({
        url: '/api/materials/list',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                materialsData = response.materials;
                displayMaterialsList(materialsData);
                populateSelects();
            }
        },
        error: function() {
            $('#materialList').html(showError('Failed to load materials'));
        }
    });
}

function displayMaterialsList(materials) {
    const $list = $('#materialList');
    $list.empty();
    
    materials.forEach(name => {
        const item = $(`
            <a href="#" class="list-group-item list-group-item-action material-item" data-name="${name}">
                ${name}
            </a>
        `);
        
        item.click(function(e) {
            e.preventDefault();
            $('.material-item').removeClass('active');
            $(this).addClass('active');
            loadMaterialDetails(name);
        });
        
        $list.append(item);
    });
}

function filterMaterials(query) {
    if (!query) {
        displayMaterialsList(materialsData);
        return;
    }
    
    const filtered = materialsData.filter(name => 
        name.toLowerCase().includes(query.toLowerCase())
    );
    displayMaterialsList(filtered);
}

// Load material details
function loadMaterialDetails(name) {
    $.ajax({
        url: `/api/materials/get/${name}`,
        method: 'GET',
        success: function(response) {
            if (response.success) {
                currentMaterial = response.material;
                displayMaterialDetails(response.material);
            }
        },
        error: function() {
            $('#materialDetails').html(showError('Failed to load material details'));
        }
    });
}

function displayMaterialDetails(material) {
    $('#materialName').html(`<i class="bi bi-info-circle"></i> ${material.name}`);
    
    let html = '<div class="row">';
    
    // Band structure properties
    html += '<div class="col-md-6">';
    html += '<h6 class="text-primary mb-3">Band Structure</h6>';
    html += createPropertyRow('Band Gap (300K)', material.Eg, 'eV');
    if (material.Eg_0K) {
        html += createPropertyRow('Band Gap (0K)', material.Eg_0K, 'eV');
    }
    html += createPropertyRow('Ec Offset', material.Ec_offset, 'eV');
    html += createPropertyRow('Ev Offset', material.Ev_offset, 'eV');
    if (material.spin_orbit_splitting) {
        html += createPropertyRow('Spin-Orbit Splitting', material.spin_orbit_splitting, 'eV');
    }
    html += '</div>';
    
    // Effective masses
    html += '<div class="col-md-6">';
    html += '<h6 class="text-primary mb-3">Effective Masses</h6>';
    if (material.me_gamma) {
        html += createPropertyRow('Electron (Γ)', material.me_gamma, 'm₀');
    }
    if (material.mhh) {
        html += createPropertyRow('Heavy Hole', material.mhh, 'm₀');
    }
    if (material.mlh) {
        html += createPropertyRow('Light Hole', material.mlh, 'm₀');
    }
    html += '</div>';
    
    html += '</div>'; // End row
    
    html += '<div class="row mt-3">';
    
    // Dielectric properties
    html += '<div class="col-md-6">';
    html += '<h6 class="text-primary mb-3">Dielectric Properties</h6>';
    if (material.epsilon_static) {
        html += createPropertyRow('Static Dielectric', material.epsilon_static, '');
    }
    if (material.epsilon_optical) {
        html += createPropertyRow('Optical Dielectric', material.epsilon_optical, '');
    }
    html += '</div>';
    
    // Lattice properties
    html += '<div class="col-md-6">';
    html += '<h6 class="text-primary mb-3">Lattice</h6>';
    if (material.lattice_constant) {
        html += createPropertyRow('Lattice Constant', material.lattice_constant, 'Å');
    }
    html += '</div>';
    
    html += '</div>'; // End row
    
    // Temperature dependence
    if (material.varshni_alpha && material.varshni_beta) {
        html += '<div class="row mt-3">';
        html += '<div class="col-12">';
        html += '<h6 class="text-primary mb-3">Temperature Dependence (Varshni)</h6>';
        html += createPropertyRow('α', material.varshni_alpha, 'eV/K');
        html += createPropertyRow('β', material.varshni_beta, 'K');
        html += '</div>';
        html += '</div>';
        
        // Show temperature calculator
        $('#tempCalculatorCard').show();
        updateTemperaturePlot();
    } else {
        $('#tempCalculatorCard').hide();
    }
    
    // Notes and reference
    if (material.notes || material.reference) {
        html += '<div class="row mt-3">';
        html += '<div class="col-12">';
        if (material.notes) {
            html += `<p class="text-muted"><strong>Notes:</strong> ${material.notes}</p>`;
        }
        if (material.reference) {
            html += `<p class="text-muted"><strong>Reference:</strong> ${material.reference}</p>`;
        }
        html += '</div>';
        html += '</div>';
    }
    
    $('#materialDetails').html(html);
}

function createPropertyRow(label, value, unit) {
    if (value === null || value === undefined) {
        return '';
    }
    
    const valueStr = typeof value === 'number' ? value.toFixed(4) : value;
    
    return `
        <div class="property-row d-flex justify-content-between">
            <span class="property-label">${label}:</span>
            <span>
                <span class="property-value">${valueStr}</span>
                ${unit ? `<span class="property-unit"> ${unit}</span>` : ''}
            </span>
        </div>
    `;
}

// Populate selects
function populateSelects() {
    const selects = ['#alloySub', '#alloyBase', '#compareMat1', '#compareMat2'];
    
    selects.forEach(sel => {
        const $select = $(sel);
        $select.find('option:not(:first)').remove();
        
        materialsData.forEach(name => {
            $select.append(`<option value="${name}">${name}</option>`);
        });
    });
}

// Show alloy calculator
function showAlloyCalculator() {
    $('#alloyCalculatorCard').slideToggle();
}

// Calculate alloy properties
function calculateAlloyProperties() {
    const mat1 = $('#alloySub').val();
    const mat2 = $('#alloyBase').val();
    const x = parseFloat($('#alloyComposition').val());
    
    if (!mat1 || !mat2) {
        alert('Please select both materials');
        return;
    }
    
    $.ajax({
        url: '/api/materials/alloy',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            material1: mat1,
            material2: mat2,
            composition: x
        }),
        success: function(response) {
            if (response.success) {
                displayAlloyResults(response.alloy);
            }
        },
        error: function(xhr) {
            alert('Error calculating alloy: ' + (xhr.responseJSON?.error || 'Unknown error'));
        }
    });
}

function displayAlloyResults(alloy) {
    let html = '<h6 class="text-success">Alloy Properties</h6>';
    html += '<div class="table-responsive">';
    html += '<table class="table table-sm table-striped">';
    html += '<thead><tr><th>Property</th><th>Value</th><th>Unit</th></tr></thead>';
    html += '<tbody>';
    
    if (alloy.Eg) {
        html += `<tr><td>Band Gap</td><td>${alloy.Eg.toFixed(4)}</td><td>eV</td></tr>`;
    }
    if (alloy.Ec_offset) {
        html += `<tr><td>Ec Offset</td><td>${alloy.Ec_offset.toFixed(4)}</td><td>eV</td></tr>`;
    }
    if (alloy.me_gamma) {
        html += `<tr><td>Electron Mass</td><td>${alloy.me_gamma.toFixed(4)}</td><td>m₀</td></tr>`;
    }
    if (alloy.lattice_constant) {
        html += `<tr><td>Lattice Constant</td><td>${alloy.lattice_constant.toFixed(4)}</td><td>Å</td></tr>`;
    }
    
    html += '</tbody></table></div>';
    
    $('#alloyResults').html(html).slideDown();
}

// Temperature calculations
function calculateTemperature() {
    if (!currentMaterial) {
        return;
    }
    
    const T = parseFloat($('#tempValue').val());
    
    // Simple calculation (should use API in production)
    if (currentMaterial.varshni_alpha && currentMaterial.varshni_beta) {
        const Eg0 = currentMaterial.Eg_0K || currentMaterial.Eg;
        const EgT = Eg0 - currentMaterial.varshni_alpha * T * T / (T + currentMaterial.varshni_beta);
        
        $('#tempResults').html(`
            <div class="alert alert-info">
                <strong>E<sub>g</sub>(${T} K) = ${EgT.toFixed(4)} eV</strong>
            </div>
        `);
    }
}

function updateTemperaturePlot() {
    if (!currentMaterial || !currentMaterial.varshni_alpha) {
        return;
    }
    
    // Generate temperature range
    const temps = [];
    const bandgaps = [];
    const Eg0 = currentMaterial.Eg_0K || currentMaterial.Eg;
    
    for (let T = 0; T <= 500; T += 5) {
        temps.push(T);
        const EgT = Eg0 - currentMaterial.varshni_alpha * T * T / (T + currentMaterial.varshni_beta);
        bandgaps.push(EgT);
    }
    
    // Create or update chart
    const ctx = $('#tempPlot')[0].getContext('2d');
    
    if (tempChart) {
        tempChart.destroy();
    }
    
    tempChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: temps,
            datasets: [{
                label: 'Band Gap (eV)',
                data: bandgaps,
                borderColor: 'rgb(75, 192, 192)',
                borderWidth: 2,
                fill: false,
                pointRadius: 0
            }]
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: `${currentMaterial.name} - Eg vs Temperature`
                }
            },
            scales: {
                x: {
                    title: {
                        display: true,
                        text: 'Temperature (K)'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: 'Band Gap (eV)'
                    }
                }
            }
        }
    });
}

// Material comparison
function showComparison() {
    $('#comparisonCard').slideToggle();
}

function compareMaterials() {
    const mat1Name = $('#compareMat1').val();
    const mat2Name = $('#compareMat2').val();
    
    if (!mat1Name || !mat2Name) {
        alert('Please select two materials');
        return;
    }
    
    // Fetch both materials
    Promise.all([
        $.ajax({ url: `/api/materials/get/${mat1Name}`, method: 'GET' }),
        $.ajax({ url: `/api/materials/get/${mat2Name}`, method: 'GET' })
    ]).then(([res1, res2]) => {
        if (res1.success && res2.success) {
            displayComparison(res1.material, res2.material);
        }
    });
}

function displayComparison(mat1, mat2) {
    let html = '<table class="table table-sm table-bordered">';
    html += '<thead class="table-light">';
    html += '<tr><th>Property</th><th>' + mat1.name + '</th><th>' + mat2.name + '</th></tr>';
    html += '</thead><tbody>';
    
    const props = [
        { key: 'Eg', label: 'Band Gap (eV)' },
        { key: 'me_gamma', label: 'Electron Mass (m₀)' },
        { key: 'mhh', label: 'Heavy Hole Mass (m₀)' },
        { key: 'mlh', label: 'Light Hole Mass (m₀)' },
        { key: 'epsilon_static', label: 'Static Dielectric' },
        { key: 'lattice_constant', label: 'Lattice Constant (Å)' }
    ];
    
    props.forEach(prop => {
        const val1 = mat1[prop.key] !== null && mat1[prop.key] !== undefined ? 
                     (typeof mat1[prop.key] === 'number' ? mat1[prop.key].toFixed(4) : mat1[prop.key]) : '-';
        const val2 = mat2[prop.key] !== null && mat2[prop.key] !== undefined ? 
                     (typeof mat2[prop.key] === 'number' ? mat2[prop.key].toFixed(4) : mat2[prop.key]) : '-';
        
        html += `<tr><td>${prop.label}</td><td>${val1}</td><td>${val2}</td></tr>`;
    });
    
    html += '</tbody></table>';
    
    $('#comparisonResults').html(html).slideDown();
}

// Save custom material
function saveCustomMaterial() {
    // This would send to API in production
    alert('Custom material feature coming soon!');
    bootstrap.Modal.getInstance($('#customMaterialModal')[0]).hide();
}
