<?php

if (!defined('ABSPATH')) exit;

add_filter('the_content', function($content) {
    if (is_singular('post') && in_the_loop() && is_main_query()) {
        $post_id = get_the_ID();

        // =====================================================================
        // 0A. VERIFICAR BLOQUEIO POR DIREITOS DE AUTOR
        // =====================================================================
        if (function_exists('imz_check_copyright_block')) {
            $block = imz_check_copyright_block($post_id);
            if ($block) return $block;
        }

        // =====================================================================
        // 0B. VERIFICAR PRE-SAVE (pré-lançamento)
        // =====================================================================
        if (function_exists('imz_check_presave_mode')) {
            $presave = imz_check_presave_mode($post_id);
            if ($presave) return $presave;
        }
        
        // =====================================================================
        // 1. L�0�7GICA DE IMPULSIONAMENTOS (SELO E FOGO)
        // =====================================================================
        $query = new WP_Query([
            'post_type' => 'impulsionamento',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'meta_query' => [
                ['key' => 'post_id_original', 'value' => $post_id],
                ['key' => 'status', 'value' => 'aprovado']
            ]
        ]);
        $boost_posts = $query->posts;
        if (function_exists('imz_boost_is_active')) {
            $boost_posts = array_values(array_filter($boost_posts, static function($boost_post) {
                return imz_boost_is_active($boost_post->ID);
            }));
        }
        $count = count($boost_posts);
        $total_mt = 0;
        $cor_forcada = '';
        $simulado = '';

        if (!empty($boost_posts)) {
            foreach ($boost_posts as $p) {
                $total_mt += (int) get_post_meta($p->ID, 'valor', true);
                if (get_post_meta($p->ID, '_boost_payment_source', true) === 'wallet') {
                    $cor_forcada = '#2563eb';
                } elseif (empty($cor_forcada)) {
                    $cor_forcada = get_post_meta($p->ID, 'cor_forcada', true);
                }
                if (empty($simulado)) {
                    $simulado = get_post_meta($p->ID, 'valor_total_simulado', true);
                }
            }
        }
        
        wp_reset_postdata();
        
        if (!empty($simulado)) {
            $total_mt = intval($simulado);
        }

        // --- Montagem do Selo de Impulsionamento ---
        $boost_badge_html = '';
        if ($count > 0) {
            // L��gica dos N��veis de Hype
            $hype_level_title = '';
            $hype_levels = get_option('imz_hype_levels', []);

            if (!empty($hype_levels)) {
                usort($hype_levels, function($a, $b) {
                    return $b['amount'] <=> $a['amount'];
                });
                foreach ($hype_levels as $level) {
                    if ($total_mt >= $level['amount']) {
                        $hype_level_title = $level['title'];
                        break; 
                    }
                }
            }
            
            $badge_text_prefix = !empty($hype_level_title) ? $hype_level_title : 'Impulsionado';
            $badge_text = esc_html($badge_text_prefix) . " ({$count}x)";
            
            // L��gica de Cores
            $cor = get_option('imz_cor_padrao', '#2563eb');
            if ($total_mt >= 3000) {
                $cor = get_option('imz_cor_3000', '#facc15');
            } elseif ($total_mt >= 1000) {
                $cor = get_option('imz_cor_1000', '#22c55e');
            }
            if (!empty($cor_forcada)) {
                $cor = $cor_forcada;
            }

            $boost_badge_html = "<div class='imz-selo-impulsionado' style='background-color: " . esc_attr($cor) . ";'>{$badge_text}</div>";
        }
        
        // --- Efeito de Fogo ---
        $fire_effect_html = '';
        if ($count > 10) {
            $gif_url = plugin_dir_url(__FILE__) . '../assets/sun.gif';
            $fire_effect_html = "<img src='{$gif_url}' style='position:absolute; top:20px; right:20px; width:80px; z-index:999; pointer-events:none;'>";
        }

        // =====================================================================
        // 2. NOVO: SELO 1MZ FOR ARTISTS (PROTE�0�5�0�1O)
        // =====================================================================
        $protection_badge_html = '';
        if (get_post_meta($post_id, '_imz_protected_for_artists', true) === 'yes') {
            $protection_badge_html = '
            <div class="imz-protection-container">
                <span class="imz-badge-protected" title="Esta musica esta a ser gerenciada pela 1MusicMoz">
                    1MZ For Artists
                </span>
            </div>';
        }

        // =====================================================================
        // 3. L�0�7GICA DO SELO YOUTUBE
        // =====================================================================
        $youtube_badge_html = '';
        $youtube_url = get_post_meta($post_id, '_imz_youtube_url', true);
        
        // Usa a fun�0�4�0�0o centralizada para dados (Titulo/Artista/Views/Thumb)
        $video_data = function_exists('imz_get_player_display_data') ? imz_get_player_display_data($post_id) : null;
        
        if (!empty($youtube_url) && $video_data && !isset($video_data['error']) && $video_data['viewCount'] > 0) {
            $formatted_views = imz_format_number_short($video_data['viewCount']);
            $youtube_badge_html = '<a href="' . esc_url($youtube_url) . '" target="_blank" rel="noopener noreferrer" class="imz-selo-youtube" title="Ver video no YouTube - ' . esc_attr(number_format($video_data['viewCount'])) . ' visualizacoes">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="play-icon"><path d="M8 5v14l11-7z"></path></svg>
                <span>L&aacute; no YouTube: ' . esc_html($formatted_views) . '</span>
            </a>';
        }
        
        // --- Selo de Plays do Player (prova social com dados próprios) ---
        $plays_badge_html = '';
        if (function_exists('imz_get_play_count') && get_post_meta($post_id, '_imz_enable_audio_player', true) === 'yes') {
            $play_count = imz_get_play_count($post_id);
            if ($play_count > 0) {
                $formatted_plays = function_exists('imz_format_number_short') ? imz_format_number_short($play_count) : number_format_i18n($play_count);
                $plays_badge_html = '<span class="imz-selo-plays" title="' . esc_attr(number_format_i18n($play_count)) . ' reproduções no site">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="play-icon"><path d="M8 5v14l11-7z"></path></svg>
                    <span>' . esc_html($formatted_plays) . ' plays</span>
                </span>';
            }
        }

        // --- Container dos Selos (Boost, Youtube e Plays) ---
        $badges_container_html = '';
        if (!empty($boost_badge_html) || !empty($youtube_badge_html) || !empty($plays_badge_html)) {
            $badges_container_html = '<div class="imz-badges-container">' . $boost_badge_html . $youtube_badge_html . $plays_badge_html . '</div>';
        }

        // =====================================================================
        // 4. L�0�7GICA DO PLAYER DE �0�9UDIO (ATUALIZADO COM ARTISTA)
        // =====================================================================
        $audio_player_html = '';
        if (get_post_meta($post_id, '_imz_enable_audio_player', true) === 'yes' && function_exists('imz_get_youtube_id_from_url')) {
            $audio_url = get_post_meta($post_id, '_imz_audio_player_url', true);
            if (empty($audio_url)) {
                $audio_url = get_post_meta($post_id, '_imz_youtube_url', true);
            }
            $video_id = imz_get_youtube_id_from_url($audio_url);

            if ($video_id) {
                // Obt��m os dados processados com prioridade (Personalizado > YouTube)
                $audio_video_data = imz_get_player_display_data($post_id);
                
                $title = $audio_video_data['title']; 
                $artist = $audio_video_data['artist']; // <--- Novo campo suportado
                $thumbnail = $audio_video_data['thumbnailUrl'];
                
                ob_start();
                ?>
                <div id="imz-audio-player-container" class="imz-player-v2" data-video-id="<?php echo esc_attr($video_id); ?>" data-post-id="<?php echo esc_attr($post_id); ?>">
                    <div class="imz-player-spinner"></div>

                    <!-- Play/Pause: botão circular vermelho -->
                    <button class="imz-player-play-pause-btn" aria-label="Reproduzir/Pausar">
                        <svg class="play-icon" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
                        <svg class="pause-icon" style="display:none;" viewBox="0 0 24 24"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/></svg>
                    </button>

                    <!-- Título + Artista -->
                    <div class="imz-player-meta">
                        <span class="imz-player-title"><?php echo esc_html($title); ?></span>
                        <span class="imz-player-artist"><?php echo esc_html($artist); ?></span>
                    </div>

                    <!-- Tempo actual -->
                    <span class="imz-player-time-current">0:00</span>

                    <!-- Barra de progresso vermelha -->
                    <div class="imz-player-progress">
                        <div class="imz-player-track"></div>
                        <div class="imz-player-fill"></div>
                        <div class="imz-player-waveform-overlay"></div>
                        <input type="range" class="imz-player-seek-slider" value="0" min="0" step="1" aria-label="Progresso">
                    </div>

                    <!-- Duração total -->
                    <span class="imz-player-time-duration">0:00</span>

                    <!-- Volume + Repeat -->
                    <div class="imz-player-controls-right">
                        <div class="imz-player-volume-control">
                            <svg class="imz-player-options-btn" viewBox="0 0 24 24"><circle cx="12" cy="12" r="2"/><circle cx="12" cy="5" r="2"/><circle cx="12" cy="19" r="2"/></svg>
                            <div class="imz-player-popup-options">
                                <input type="range" class="imz-player-volume-slider" min="0" max="100" value="100">
                                <button class="imz-player-repeat-btn active" title="Repetir (Ativado)">
                                    <svg viewBox="0 0 24 24"><path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"/></svg>
                                </button>
                            </div>
                        </div>
                    </div>

                    <div id="youtube-iframe-placeholder"></div>
                </div>
                <?php
                $audio_player_html = ob_get_clean();
            }
        }
        
        // =====================================================================
        // 5. QUADRO DE L�0�1DERES (TOP IMPULSIONADORES)
        // =====================================================================
        $leaderboard_html = function_exists('imz_get_leaderboard_html') ? imz_get_leaderboard_html($post_id) : '';
        
        // =====================================================================
        // 6. BOT�0�1O E MODAL DE REPORTE
        // =====================================================================
        $report_button_html = '';
        $report_modal_html = '';

        if (function_exists('imz_get_report_modal_html')) {
            $report_modal_html = imz_get_report_modal_html($post_id);
            $report_button_html = '
                <div class="imz-report-button-container" style="margin-top: 30px; padding-top: 15px; border-top: 1px solid var(--imz-border-color);">
                    <p style="font-size: 14px; color: var(--imz-color-text-light); margin-bottom: 10px;">Encontrou algum problema com esta musica ou download?</p>
                    <a href="#" id="imz-open-report-modal" class="imz-report-button" spellcheck="false">Relatar Problema</a>
                </div>';
        }

        // =====================================================================
        // 7. MONTAGEM FINAL DO CONTE�0�3DO
        // =====================================================================
        // Ordem: Fogo > Selo Prote�0�4�0�0o > Outros Selos > Player > Conte��do Original > L��deres > Reportar > Modal
        return $fire_effect_html . $protection_badge_html . $badges_container_html . $audio_player_html . $content . $leaderboard_html . $report_button_html . $report_modal_html;
    }
    return $content;
}, 10);
?>