// Dashboard functionality
let selectedOption = null;
let currentScript = '';
let characterVoices = {};

async function loadUserData() {
    if (!currentUser) return;
    
    try {
        // Use mock API for demo
        const result = await window.mockAPI.getUserData(currentUser.id);
        
        if (result.success) {
            const userData = result.user;
            document.getElementById('credit-amount').textContent = userData.credits;
            document.getElementById('profile-name').textContent = userData.full_name;
            document.getElementById('profile-email').textContent = userData.email;
            document.getElementById('profile-credits').textContent = userData.credits;
            document.getElementById('profile-date').textContent = formatDate(userData.created_at);
        }
    } catch (error) {
        console.error('Error loading user data:', error);
    }
}

function showSection(sectionName) {
    // Hide all sections
    document.querySelectorAll('.content-section').forEach(section => {
        section.classList.remove('active');
    });
    
    // Show selected section
    document.getElementById(sectionName + '-section').classList.add('active');
    
    // Update sidebar
    document.querySelectorAll('.sidebar-menu a').forEach(link => {
        link.classList.remove('active');
    });
    event.target.classList.add('active');
    
    // Load section data
    if (sectionName === 'podcasts') {
        loadUserPodcasts();
    }
}

function selectOption(option) {
    selectedOption = option;
    
    // Update UI
    document.querySelectorAll('.option-card').forEach(card => {
        card.classList.remove('selected');
    });
    event.target.closest('.option-card').classList.add('selected');
    
    // Show appropriate input section
    document.getElementById('manual-input').style.display = option === 'manual' ? 'block' : 'none';
    document.getElementById('ai-input').style.display = option === 'ai' ? 'block' : 'none';
}

async function processScript() {
    const script = document.getElementById('manual-script').value.trim();
    
    if (!script) {
        showNotification('Lütfen bir senaryo girin', 'error');
        return;
    }
    
    // Validate script format
    if (!validateScriptFormat(script)) {
        showNotification('Geçersiz format! Örnek: Ali: Merhaba! Ayşe: Selam!', 'error');
        return;
    }
    
    currentScript = script;
    showVoiceSelection();
}

async function generateWithAI() {
    const topic = document.getElementById('ai-topic').value.trim();
    
    if (!topic) {
        showNotification('Lütfen bir konu girin', 'error');
        return;
    }
    
    // Check credits
    const hasCredits = await checkAndDeductCredits(CREDIT_COSTS.AI_TEXT_GENERATION);
    if (!hasCredits) return;
    
    try {
        showNotification('AI ile metin oluşturuluyor...', 'info');
        
        // Use mock API for demo
        const result = await window.mockAPI.generateScript(topic);
        
        if (result.success) {
            currentScript = result.script;
            showVoiceSelection();
            showNotification('Metin başarıyla oluşturuldu!', 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        showNotification('AI metin oluşturma hatası: ' + error.message, 'error');
        // Refund credits on error
        await refundCredits(CREDIT_COSTS.AI_TEXT_GENERATION);
    }
}

function validateScriptFormat(script) {
    // Check if script contains character names followed by colons
    const lines = script.split('\n').filter(line => line.trim());
    return lines.every(line => line.includes(':') && line.indexOf(':') > 0);
}

function extractCharacters(script) {
    const characters = new Set();
    const lines = script.split('\n').filter(line => line.trim());
    
    lines.forEach(line => {
        const colonIndex = line.indexOf(':');
        if (colonIndex > 0) {
            const character = line.substring(0, colonIndex).trim();
            characters.add(character);
        }
    });
    
    return Array.from(characters);
}

async function showVoiceSelection() {
    const characters = extractCharacters(currentScript);
    const charactersList = document.getElementById('characters-list');
    
    charactersList.innerHTML = '';
    
    // Get available voices from ElevenLabs
    const voices = await getAvailableVoices();
    
    characters.forEach(character => {
        const characterDiv = document.createElement('div');
        characterDiv.className = 'character-voice';
        characterDiv.innerHTML = `
            <h4>${character}</h4>
            <div class="voice-options" data-character="${character}">
                ${voices.map(voice => `
                    <div class="voice-option" data-voice-id="${voice.voice_id}" onclick="selectVoice('${character}', '${voice.voice_id}', this)">
                        <p><strong>${voice.name}</strong></p>
                        <p>${voice.labels.gender} - ${voice.labels.accent}</p>
                        <button onclick="playVoiceSample('${voice.voice_id}'); event.stopPropagation();">
                            <i class="fas fa-play"></i>
                        </button>
                    </div>
                `).join('')}
            </div>
        `;
        charactersList.appendChild(characterDiv);
    });
    
    document.getElementById('voice-selection').style.display = 'block';
    document.getElementById('manual-input').style.display = 'none';
    document.getElementById('ai-input').style.display = 'none';
}

async function getAvailableVoices() {
    // Mock voices for demo - in real implementation, call ElevenLabs API
    return [
        { voice_id: 'voice1', name: 'Sarah', labels: { gender: 'Female', accent: 'American' } },
        { voice_id: 'voice2', name: 'John', labels: { gender: 'Male', accent: 'British' } },
        { voice_id: 'voice3', name: 'Maria', labels: { gender: 'Female', accent: 'Spanish' } },
        { voice_id: 'voice4', name: 'David', labels: { gender: 'Male', accent: 'Australian' } }
    ];
}

function selectVoice(character, voiceId, element) {
    // Remove previous selection for this character
    const characterOptions = element.parentElement;
    characterOptions.querySelectorAll('.voice-option').forEach(option => {
        option.classList.remove('selected');
    });
    
    // Select current voice
    element.classList.add('selected');
    characterVoices[character] = voiceId;
    
    // Check if all characters have voices selected
    const characters = extractCharacters(currentScript);
    const allSelected = characters.every(char => characterVoices[char]);
    
    const generateBtn = document.querySelector('.btn-generate');
    generateBtn.disabled = !allSelected;
    generateBtn.style.opacity = allSelected ? '1' : '0.5';
}

async function playVoiceSample(voiceId) {
    try {
        // In real implementation, call ElevenLabs API to get voice sample
        showNotification('Ses örneği çalınıyor...', 'info');
    } catch (error) {
        showNotification('Ses örneği çalınamadı', 'error');
    }
}

async function generatePodcast() {
    // Check if all voices are selected
    const characters = extractCharacters(currentScript);
    const allSelected = characters.every(char => characterVoices[char]);
    
    if (!allSelected) {
        showNotification('Lütfen tüm karakterler için ses seçin', 'error');
        return;
    }
    
    // Check credits
    const hasCredits = await checkAndDeductCredits(CREDIT_COSTS.PODCAST_GENERATION);
    if (!hasCredits) return;
    
    try {
        // Show progress
        document.getElementById('voice-selection').style.display = 'none';
        document.getElementById('generation-progress').style.display = 'block';
        
        // Simulate progress
        let progress = 0;
        const progressFill = document.querySelector('.progress-fill');
        const progressText = document.getElementById('progress-text');
        
        const progressInterval = setInterval(() => {
            progress += Math.random() * 15;
            if (progress > 90) progress = 90;
            
            progressFill.style.width = progress + '%';
            
            if (progress < 30) {
                progressText.textContent = 'Ses dosyaları oluşturuluyor...';
            } else if (progress < 60) {
                progressText.textContent = 'Ses dosyaları birleştiriliyor...';
            } else {
                progressText.textContent = 'Son işlemler yapılıyor...';
            }
        }, 500);
        
        // Call backend to generate podcast
        // Use mock API for demo
        const result = await window.mockAPI.generatePodcast(currentScript, characterVoices);
        
        clearInterval(progressInterval);
        progressFill.style.width = '100%';
        
        if (result.success) {
            // Save podcast to database
            // Already saved in mock API
            
            // Show result
            setTimeout(() => {
                document.getElementById('generation-progress').style.display = 'none';
                document.getElementById('podcast-result').style.display = 'block';
                document.getElementById('final-podcast').src = result.podcast_url;
            }, 1000);
            
            showNotification('Podcast başarıyla oluşturuldu!', 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        showNotification('Podcast oluşturma hatası: ' + error.message, 'error');
        // Refund credits on error
        await refundCredits(CREDIT_COSTS.PODCAST_GENERATION);
        resetForm();
    }
}

async function savePodcast(podcastUrl, title) {
    try {
        const { error } = await supabase
            .from('podcasts')
            .insert([
                {
                    user_id: currentUser.id,
                    title: title || 'Untitled Podcast',
                    script: currentScript,
                    audio_url: podcastUrl,
                    voices: characterVoices,
                    duration: '00:00', // Will be updated after processing
                    voice_settings: {
                        stability: 0.5,
                        similarity_boost: 0.5
                    }
                }
            ]);
        
        if (error) throw error;
    } catch (error) {
        console.error('Error saving podcast:', error);
    }
}

async function combineAudioFiles(audioBuffers) {
    // Simple concatenation for demo
    // In production, use proper audio processing
    const totalLength = audioBuffers.reduce((sum, buffer) => sum + buffer.byteLength, 0);
    const combined = new Uint8Array(totalLength);
    
    let offset = 0;
    audioBuffers.forEach(buffer => {
        combined.set(new Uint8Array(buffer), offset);
        offset += buffer.byteLength;
    });
    
    return combined.buffer;
}

async function refundCredits(amount) {
    // Mock refund
    const user = mockDatabase.users.find(u => u.id === currentUser.id);
    if (user) {
        user.credits += amount;
        document.getElementById('credit-amount').textContent = user.credits;
    }
}

async function loadUserPodcasts() {
    try {
        // Use mock API for demo
        const result = await window.mockAPI.getUserPodcasts(currentUser.id);
        const podcasts = result.podcasts;
        
        const podcastsList = document.getElementById('podcasts-list');
        podcastsList.innerHTML = '';
        
        if (podcasts && podcasts.length > 0) {
            podcasts.forEach(podcast => {
                const podcastCard = document.createElement('div');
                podcastCard.className = 'podcast-card';
                podcastCard.innerHTML = `
                    <h3>${podcast.title}</h3>
                    <p>Süre: ${podcast.duration}</p>
                    <p>Oluşturulma: ${formatDate(podcast.created_at)}</p>
                    <audio controls>
                        <source src="${podcast.audio_url}" type="audio/mpeg">
                    </audio>
                    <div class="podcast-actions">
                        <button onclick="downloadPodcastFile('${podcast.audio_url}', '${podcast.title}')">
                            <i class="fas fa-download"></i> İndir
                        </button>
                        <button onclick="deletePodcast('${podcast.id}')" class="btn-danger">
                            <i class="fas fa-trash"></i> Sil
                        </button>
                    </div>
                `;
                podcastsList.appendChild(podcastCard);
            });
        } else {
            podcastsList.innerHTML = '<p>Henüz podcast oluşturmadınız.</p>';
        }
    } catch (error) {
        showNotification('Podcastler yüklenirken hata oluştu', 'error');
    }
}

function selectPackage(credits, price) {
    showNotification(`${credits} kredi için ${price}₺ ödeme yapmanız gerekiyor. Dekont yükleme bölümünden dekontunuzu yükleyebilirsiniz.`, 'info');
}

async function uploadReceipt(input) {
    const file = input.files[0];
    if (!file) return;
    
    try {
        // Upload file to Supabase storage
        const fileName = `receipt_${currentUser.id}_${Date.now()}.${file.name.split('.').pop()}`;
        
        const { data, error } = await supabase.storage
            .from('receipts')
            .upload(fileName, file);
        
        if (error) throw error;
        
        // Save receipt record
        const { error: dbError } = await supabase
            .from('receipts')
            .insert([
                {
                    user_id: currentUser.id,
                    file_path: data.path,
                    status: 'pending'
                }
            ]);
        
        if (dbError) throw dbError;
        
        showNotification('Dekont başarıyla yüklendi! Admin onayı bekleniyor.', 'success');
        input.value = '';
    } catch (error) {
        showNotification('Dekont yükleme hatası: ' + error.message, 'error');
    }
}

function downloadPodcast() {
    const audio = document.getElementById('final-podcast');
    const link = document.createElement('a');
    link.href = audio.src;
    link.download = 'podcast.mp3';
    link.click();
}

function downloadPodcastFile(url, title) {
    const link = document.createElement('a');
    link.href = url;
    link.download = `${title}.mp3`;
    link.click();
}

async function deletePodcast(podcastId) {
    if (!confirm('Bu podcast\'i silmek istediğinizden emin misiniz?')) return;
    
    try {
        const { error } = await supabase
            .from('podcasts')
            .delete()
            .eq('id', podcastId);
        
        if (error) throw error;
        
        showNotification('Podcast silindi', 'success');
        loadUserPodcasts();
    } catch (error) {
        showNotification('Silme hatası: ' + error.message, 'error');
    }
}

function resetForm() {
    selectedOption = null;
    currentScript = '';
    characterVoices = {};
    
    // Hide all sections except create options
    document.getElementById('manual-input').style.display = 'none';
    document.getElementById('ai-input').style.display = 'none';
    document.getElementById('voice-selection').style.display = 'none';
    document.getElementById('generation-progress').style.display = 'none';
    document.getElementById('podcast-result').style.display = 'none';
    
    // Reset forms
    document.getElementById('manual-script').value = '';
    document.getElementById('ai-topic').value = '';
    
    // Reset option cards
    document.querySelectorAll('.option-card').forEach(card => {
        card.classList.remove('selected');
    });
}

// Initialize dashboard
document.addEventListener('DOMContentLoaded', async function() {
    if (window.location.pathname.includes('dashboard.html')) {
        const user = await checkAuth();
        if (user) {
            await loadUserData();
        }
    }
});