<?php
// mahamudfutureit_tts_player.php
// আধুনিক TTS প্লেয়ার

require_once __DIR__ . '/mahamudfutureit_tts_config.php';

// TTS বন্ধ থাকলে কিছু দেখাবে না
if (!mahamudfutureit_is_tts_enabled()) {
    return;
}

// পোস্টের তথ্য
global $tts_post_title, $tts_post_content, $tts_post_image;
$tts_post_title = $tts_post_title ?? 'অডিও নিউজ';
$tts_post_content = $tts_post_content ?? '';
$tts_post_image = $tts_post_image ?? '';
?>

<style>
.mahamudfutureit-tts-container {
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 9999;
    width: 340px;
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
    border-radius: 16px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.3);
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.mahamudfutureit-tts-player {
    display: flex;
    padding: 12px;
    gap: 12px;
}
.mahamudfutureit-tts-album {
    width: 55px;
    height: 55px;
    border-radius: 12px;
    background-size: cover;
    background-position: center;
    flex-shrink: 0;
    background-color: #2d2d44;
}
.mahamudfutureit-tts-controls {
    flex: 1;
}
.mahamudfutureit-tts-waveform {
    display: flex;
    align-items: center;
    gap: 3px;
    height: 28px;
}
.mahamudfutureit-tts-waveform span {
    width: 4px;
    background: #4a9eff;
    border-radius: 2px;
}
.mahamudfutureit-tts-waveform.playing span {
    animation: mahamudfutureit-wave 0.8s ease infinite alternate;
}
.mahamudfutureit-tts-waveform.playing span:nth-child(1) { animation-delay: 0s; }
.mahamudfutureit-tts-waveform.playing span:nth-child(2) { animation-delay: 0.1s; }
.mahamudfutureit-tts-waveform.playing span:nth-child(3) { animation-delay: 0.2s; }
.mahamudfutureit-tts-waveform.playing span:nth-child(4) { animation-delay: 0.3s; }
.mahamudfutureit-tts-waveform.playing span:nth-child(5) { animation-delay: 0.4s; }
.mahamudfutureit-tts-waveform.playing span:nth-child(6) { animation-delay: 0.5s; }
.mahamudfutureit-tts-waveform.playing span:nth-child(7) { animation-delay: 0.6s; }
.mahamudfutureit-tts-waveform.playing span:nth-child(8) { animation-delay: 0.7s; }
.mahamudfutureit-tts-waveform.playing span:nth-child(9) { animation-delay: 0.8s; }
.mahamudfutureit-tts-waveform.playing span:nth-child(10) { animation-delay: 0.9s; }
@keyframes mahamudfutureit-wave {
    0% { height: 6px; }
    100% { height: 24px; }
}
.mahamudfutureit-tts-time {
    display: flex;
    justify-content: space-between;
    font-size: 9px;
    color: #aaa;
    margin: 5px 0;
}
.mahamudfutureit-tts-progress {
    width: 100%;
    height: 3px;
    background: #333;
    border-radius: 2px;
    cursor: pointer;
}
.mahamudfutureit-tts-progress-bar {
    width: 0%;
    height: 100%;
    background: #4a9eff;
    border-radius: 2px;
}
.mahamudfutureit-tts-buttons {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 8px;
}
.mahamudfutureit-tts-buttons i {
    cursor: pointer;
    font-size: 16px;
    color: white;
}
.mahamudfutureit-tts-play {
    width: 32px;
    height: 32px;
    background: #4a9eff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}
.mahamudfutureit-tts-speed {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
}
.mahamudfutureit-tts-speed span {
    font-size: 7px;
    color: #aaa;
    margin-top: 2px;
}
@media (max-width: 768px) {
    .mahamudfutureit-tts-container {
        width: calc(100% - 30px);
        left: 15px;
        right: 15px;
        bottom: 10px;
    }
}
</style>

<div class="mahamudfutureit-tts-container" id="mahamudfutureitTTSContainer">
    <div class="mahamudfutureit-tts-player">
        <div class="mahamudfutureit-tts-album" id="mahamudfutureitTTSAlbum" style="background-image: url('<?php echo htmlspecialchars($tts_post_image); ?>');">
        </div>
        <div class="mahamudfutureit-tts-controls">
            <div style="overflow: hidden; margin-bottom: 5px;">
                <marquee scrollamount="2" style="font-size: 11px; color: #e0e0e0; font-weight: 500;" id="mahamudfutureitTTSTitle">
                    <?php echo htmlspecialchars($tts_post_title); ?>
                </marquee>
            </div>
            <div class="mahamudfutureit-tts-waveform" id="mahamudfutureitTTSWaveform">
                <?php for($i=0;$i<10;$i++) echo '<span></span>'; ?>
            </div>
            <div class="mahamudfutureit-tts-time">
                <span id="mahamudfutureitTTSCurrent">0:00</span>
                <span id="mahamudfutureitTTSTotal">0:00</span>
            </div>
            <div class="mahamudfutureit-tts-progress" id="mahamudfutureitTTSProgress">
                <div class="mahamudfutureit-tts-progress-bar" id="mahamudfutureitTTSProgressBar"></div>
            </div>
            <div class="mahamudfutureit-tts-buttons">
                <div class="mahamudfutureit-tts-speed" id="mahamudfutureitTTSSpeed">
                    <i class="fas fa-tachometer-alt"></i>
                    <span id="mahamudfutureitTTSSpeedText">1.0x</span>
                </div>
                <i class="fas fa-backward" id="mahamudfutureitTTSPrev"></i>
                <div class="mahamudfutureit-tts-play" id="mahamudfutureitTTSPlayBtn">
                    <i class="fas fa-play" id="mahamudfutureitTTSPlayIcon"></i>
                </div>
                <i class="fas fa-forward" id="mahamudfutureitTTSNext"></i>
                <i class="fas fa-stop" id="mahamudfutureitTTSStop"></i>
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    const postContent = <?php echo json_encode($tts_post_content); ?>;
    const apiUrl = '/mahamudfutureit_tts_api.php';
    
    if (!postContent || postContent.length < 30) return;
    
    let textChunks = [];
    let currentIndex = 0;
    let currentAudio = new Audio();
    let isPlaying = false;
    let isPaused = false;
    let chunkDurations = [];
    let totalDuration = 0;
    let progressInterval;
    let currentSpeed = 1.0;
    
    const waveform = document.getElementById('mahamudfutureitTTSWaveform');
    const playIcon = document.getElementById('mahamudfutureitTTSPlayIcon');
    const progressBar = document.getElementById('mahamudfutureitTTSProgressBar');
    const currentTimeEl = document.getElementById('mahamudfutureitTTSCurrent');
    const totalTimeEl = document.getElementById('mahamudfutureitTTSTotal');
    const speedBtn = document.getElementById('mahamudfutureitTTSSpeed');
    const speedText = document.getElementById('mahamudfutureitTTSSpeedText');
    const progressContainer = document.getElementById('mahamudfutureitTTSProgress');
    const playBtn = document.getElementById('mahamudfutureitTTSPlayBtn');
    const prevBtn = document.getElementById('mahamudfutureitTTSPrev');
    const nextBtn = document.getElementById('mahamudfutureitTTSNext');
    const stopBtn = document.getElementById('mahamudfutureitTTSStop');
    const marquee = document.getElementById('mahamudfutureitTTSTitle');
    
    const speeds = [0.75, 1.0, 1.25, 1.5];
    let speedIndex = 1;
    
    function formatTime(sec) {
        if (isNaN(sec) || sec < 0) return '0:00';
        let m = Math.floor(sec / 60);
        let s = Math.floor(sec % 60);
        return m + ':' + (s < 10 ? '0' + s : s);
    }
    
    function splitText(text) {
        text = text.replace(/\n/g, ' ');
        let sentences = text.split(/(?<=[।?!;:])/g);
        let chunks = [];
        for (let s of sentences) {
            s = s.trim();
            if (!s) continue;
            if (s.length > 200) {
                let words = s.split(' ');
                let current = '';
                for (let w of words) {
                    if ((current + ' ' + w).length <= 200) {
                        current += (current ? ' ' : '') + w;
                    } else {
                        if (current) chunks.push(current);
                        current = w;
                    }
                }
                if (current) chunks.push(current);
            } else {
                chunks.push(s);
            }
        }
        return chunks;
    }
    
    function estimateDurations(chunks) {
        let durations = [], total = 0;
        for (let c of chunks) {
            let d = Math.max(1.5, c.length / 10);
            durations.push(d);
            total += d;
        }
        return { durations, total };
    }
    
    function playChunk(startTime = 0) {
        if (currentIndex >= textChunks.length || currentIndex < 0) {
            stopTTS();
            return;
        }
        
        isPlaying = true;
        isPaused = false;
        playIcon.className = 'fas fa-pause';
        waveform.classList.add('playing');
        marquee.start();
        
        currentAudio.pause();
        let url = apiUrl + '?q=' + encodeURIComponent(textChunks[currentIndex]);
        currentAudio.src = url;
        currentAudio.playbackRate = currentSpeed;
        currentAudio.preservesPitch = true;
        
        currentAudio.onended = function() {
            currentIndex++;
            playChunk();
        };
        
        currentAudio.onerror = function() {
            currentIndex++;
            playChunk();
        };
        
        currentAudio.onloadedmetadata = function() {
            if (startTime > 0) currentAudio.currentTime = startTime;
            currentAudio.play();
        };
        
        startProgress();
    }
    
    function startProgress() {
        clearInterval(progressInterval);
        progressInterval = setInterval(() => {
            if (!isPlaying || isPaused) return;
            let elapsed = 0;
            for (let i = 0; i < currentIndex; i++) elapsed += chunkDurations[i];
            elapsed += currentAudio.currentTime;
            currentTimeEl.innerText = formatTime(elapsed);
            let percent = (elapsed / totalDuration) * 100;
            if (percent > 100) percent = 100;
            progressBar.style.width = percent + '%';
        }, 200);
    }
    
    function stopTTS() {
        if (currentAudio) {
            currentAudio.pause();
            currentAudio.currentTime = 0;
        }
        currentIndex = 0;
        isPlaying = false;
        isPaused = false;
        clearInterval(progressInterval);
        progressBar.style.width = '0%';
        currentTimeEl.innerText = '0:00';
        playIcon.className = 'fas fa-play';
        waveform.classList.remove('playing');
        marquee.stop();
    }
    
    function startTTS() {
        stopTTS();
        textChunks = splitText(postContent);
        if (textChunks.length === 0) return;
        
        let { durations, total } = estimateDurations(textChunks);
        chunkDurations = durations;
        totalDuration = total;
        totalTimeEl.innerText = formatTime(totalDuration);
        currentIndex = 0;
        playChunk();
    }
    
    playBtn.onclick = function() {
        if (isPlaying && !isPaused) {
            currentAudio.pause();
            isPaused = true;
            playIcon.className = 'fas fa-play';
            waveform.classList.remove('playing');
            marquee.stop();
        } else if (isPlaying && isPaused) {
            currentAudio.play();
            isPaused = false;
            playIcon.className = 'fas fa-pause';
            waveform.classList.add('playing');
            marquee.start();
        } else {
            startTTS();
        }
    };
    
    nextBtn.onclick = function() { if (isPlaying) { currentIndex++; playChunk(); } };
    prevBtn.onclick = function() { if (isPlaying) { if (currentIndex > 0) { currentIndex--; playChunk(); } else if (currentAudio) currentAudio.currentTime = 0; } };
    stopBtn.onclick = stopTTS;
    
    speedBtn.onclick = function() {
        speedIndex = (speedIndex + 1) % speeds.length;
        currentSpeed = speeds[speedIndex];
        speedText.innerText = currentSpeed + 'x';
        if (currentAudio) currentAudio.playbackRate = currentSpeed;
    };
    
    progressContainer.onclick = function(e) {
        if (!totalDuration) return;
        let rect = progressContainer.getBoundingClientRect();
        let percent = (e.clientX - rect.left) / rect.width;
        let target = percent * totalDuration;
        let acc = 0;
        for (let i = 0; i < chunkDurations.length; i++) {
            if (acc + chunkDurations[i] >= target) {
                currentIndex = i;
                playChunk(target - acc);
                return;
            }
            acc += chunkDurations[i];
        }
    };
    
    marquee.stop();
})();
</script>