// Tooltip functions
function showTooltip(event, item) {
    const tooltip = document.getElementById('itemTooltip');
    const rarityColors = {
        common: '#9e9e9e',
        uncommon: '#4caf50',
        rare: '#2196f3',
        epic: '#9c27b0',
        legendary: '#ff9800'
    };
    
    document.getElementById('tooltipTitle').textContent = item.name;
    document.getElementById('tooltipTitle').style.color = rarityColors[item.rarity] || '#fff';
    document.getElementById('tooltipSubtitle').textContent = item.subtitle;
    document.getElementById('tooltipStats').innerHTML = item.stat ? `<div class="tooltip-stat">${item.stat}</div>` : '';
    document.getElementById('tooltipDesc').textContent = item.description;
    
    if (item.image_path) {
        document.getElementById('tooltipImg').src = item.image_path;
        document.getElementById('tooltipImg').style.display = 'block';
    } else {
        document.getElementById('tooltipImg').style.display = 'none';
    }
    
    tooltip.style.display = 'block';
    tooltip.style.left = (event.clientX + 10) + 'px';
    tooltip.style.top = (event.clientY + 10) + 'px';
}

function hideTooltip() {
    document.getElementById('itemTooltip').style.display = 'none';
}

// Modal functions
function showModal(title, content) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').innerHTML = content;
    document.getElementById('modal').style.display = 'flex';
}

function closeModal(event) {
    if (!event || event.target.id === 'modal') {
        document.getElementById('modal').style.display = 'none';
    }
}

// Image preview for forms
function previewImage(input, previewId) {
    const preview = document.getElementById(previewId);
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// Confirm action
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

// AJAX helper
function ajaxRequest(url, method, data, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    
    if (method === 'POST' && !(data instanceof FormData)) {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            callback(xhr.responseText);
        }
    };
    
    xhr.send(data);
}

// Complete habit via AJAX
function completeHabit(habitId) {
    const formData = new FormData();
    formData.append('action', 'complete_habit');
    formData.append('habit_id', habitId);
    
    ajaxRequest('ajax.php', 'POST', formData, function(response) {
        const data = JSON.parse(response);
        if (data.success) {
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    });
}

// Complete bounty via AJAX
function completeBounty(bountyId) {
    const formData = new FormData();
    formData.append('action', 'complete_bounty');
    formData.append('bounty_id', bountyId);
    
    ajaxRequest('ajax.php', 'POST', formData, function(response) {
        const data = JSON.parse(response);
        if (data.success) {
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    });
}

// Use item via AJAX
function useItem(itemId) {
    ajaxRequest('ajax.php?action=get_item&item_id=' + itemId, 'GET', null, function(response) {
        const item = JSON.parse(response);
        if (item.success) {
            let content = `
                <div style="text-align: center;">
                    ${item.data.image_path ? `<img src="${item.data.image_path}" style="width: 100px; height: 100px; object-fit: cover; border-radius: 5px; margin-bottom: 15px; border: 2px solid var(--gold);">` : ''}
                    <p style="margin-bottom: 10px;"><strong>${item.data.subtitle}</strong></p>
                    <p style="color: #4caf50; margin-bottom: 10px;">${item.data.stat_effect || ''}</p>
                    <p style="color: #888; margin-bottom: 20px;">${item.data.description}</p>
                    <p style="color: #666; font-size: 0.9rem;">Quantity: ${item.data.quantity}</p>
                </div>
            `;
            showModal(item.data.name, content);
        }
    });
}

// Show day details in calendar
function showDayDetails(year, month, day) {
    const date = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    ajaxRequest('ajax.php?action=get_day_details&date=' + date, 'GET', null, function(response) {
        const data = JSON.parse(response);
        if (data.success) {
            let content = `
                <div style="text-align: center; margin-bottom: 20px;">
                    <h3 style="color: var(--gold);">${data.champion.name}'s Day</h3>
                    <p style="color: #888;">${date}</p>
                </div>
            `;
            
            if (data.completions.length === 0) {
                content += '<p style="color: #666; text-align: center;">No quests completed this day</p>';
            } else {
                content += '<h4 style="color: var(--gold); margin-bottom: 10px;">Completed Quests:</h4>';
                content += data.completions.map(c => `
                    <div style="padding: 8px; background: rgba(76,175,80,0.2); margin: 5px 0; border-radius: 5px; display: flex; align-items: center; gap: 10px;">
                        ${c.image_path ? `<img src="${c.image_path}" style="width: 30px; height: 30px; object-fit: cover; border-radius: 3px;">` : ''}
                        ✓ ${c.name}
                    </div>
                `).join('');
            }
            
            showModal('Quest Log', content);
        }
    });
}


