<?php
/**
 * Área Art Tracks do novo painel 1MZ For Artists.
 */

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

function rmbz_art_tracks_current_track_id( $telemovel ) {
    if ( ! function_exists( 'rmbz_artists_ensure_wp_user' ) ) {
        return 0;
    }

    $user_id = rmbz_artists_ensure_wp_user( $telemovel );
    if ( ! $user_id ) {
        return 0;
    }

    $track_id = function_exists( 'rmbz_artists_get_art_track_for_user' )
        ? rmbz_artists_get_art_track_for_user( $user_id )
        : 0;

    if ( ! $track_id && function_exists( 'rmbz_artists_link_art_track_for_account' ) ) {
        $track_id = rmbz_artists_link_art_track_for_account( $telemovel, $user_id );
    }

    return absint( $track_id );
}

function rmbz_render_art_tracks_account( $telemovel ) {
    $track_id = rmbz_art_tracks_current_track_id( $telemovel );
    $native_available = function_exists( 'rmbz_art_track_artist_data' ) && rmbz_art_track_is_valid( $track_id, true );
    $legacy_available = function_exists( 'imz_get_artista' ) && function_exists( 'imz_get_ids_musicas_do_artista' );
    if ( ! $track_id || ( ! $native_available && ! $legacy_available ) ) {
        return '<div class="art-track-empty card"><span class="ms art-track-empty-icon">person</span><div><span class="art-track-eyebrow">CATÁLOGO DO ARTISTA</span><h3>Estamos a preparar o teu Art Track</h3><p>A tua conta 1MZ já está ativa. Quando a equipa concluir o vínculo, as músicas publicadas no site aparecerão automaticamente nesta área.</p></div></div>';
    }

    $artist = $native_available ? rmbz_art_track_artist_data( $track_id ) : imz_get_artista( $track_id );
    if ( ! $artist ) {
        return '<div class="art-track-empty card"><span class="ms art-track-empty-icon">library_music</span><div><h3>Art Track indisponível</h3><p>Não foi possível carregar o catálogo associado a esta conta.</p></div></div>';
    }

    $music_ids = $native_available ? rmbz_art_track_music_ids( $track_id ) : imz_get_ids_musicas_do_artista( $track_id );
    $musics = empty( $music_ids ) ? [] : get_posts( [
        'post_type'              => 'post',
        'post_status'            => 'publish',
        'post__in'               => $music_ids,
        'posts_per_page'         => -1,
        'orderby'                => 'date',
        'order'                  => 'DESC',
        'no_found_rows'          => true,
        'update_post_term_cache' => false,
    ] );
    if ( function_exists( 'rmbz_site_publication_is_visible' ) ) {
        $musics = array_values( array_filter( $musics, static function( $music ) {
            return rmbz_site_publication_is_visible( $music->ID );
        } ) );
    }

    $principal = 0;
    $features = 0;
    $downloads = 0;
    $plays = 0;
    foreach ( $musics as $music ) {
        $native_role = $native_available && function_exists( 'rmbz_art_track_music_role' ) ? rmbz_art_track_music_role( $track_id, $music->ID ) : '';
        if ( $native_role === 'primary' || ( $native_role === '' && (int) get_post_meta( $music->ID, '_imz_artista_id', true ) === $track_id ) ) {
            $principal++;
        } else {
            $features++;
        }
        $downloads += (int) get_post_meta( $music->ID, '_imz_download_count', true );
        $plays += function_exists( 'imz_get_play_count' ) ? (int) imz_get_play_count( $music->ID ) : 0;
    }

    $photo = (string) ( $artist['photo'] ?? '' );
    $initial = function_exists( 'mb_substr' ) ? mb_substr( (string) $artist['nome'], 0, 1 ) : substr( (string) $artist['nome'], 0, 1 );

    ob_start();
    ?>
    <div class="art-track-page">
        <section class="art-track-hero card">
            <div class="art-track-avatar">
                <?php if ( $photo ): ?><img src="<?php echo esc_url( $photo ); ?>" alt=""><?php else: ?><span><?php echo esc_html( strtoupper( $initial ) ); ?></span><?php endif; ?>
            </div>
            <div class="art-track-identity">
                <div class="art-track-label"><span class="ms">verified</span> ART TRACK VINCULADO</div>
                <h2><?php echo esc_html( $artist['nome'] ); ?></h2>
                <p><?php echo ! empty( $artist['bio'] ) ? esc_html( $artist['bio'] ) : 'Catálogo oficial publicado pela 1MZ.'; ?></p>
                <div class="art-track-tags">
                    <?php if ( ! empty( $artist['genero'] ) ): ?><span><?php echo esc_html( $artist['genero'] ); ?></span><?php endif; ?>
                    <?php if ( ! empty( $artist['pais'] ) ): ?><span><?php echo esc_html( $artist['pais'] ); ?></span><?php endif; ?>
                    <span><?php echo count( $musics ); ?> <?php echo count( $musics ) === 1 ? 'música publicada' : 'músicas publicadas'; ?></span>
                </div>
            </div>
            <div class="art-track-linked"><span class="ms">link</span><div><strong>Conta associada</strong><small>Sincronização automática</small></div></div>
        </section>

        <section class="art-track-metrics">
            <article class="card"><span class="ms">album</span><div><small>CATÁLOGO</small><strong><?php echo count( $musics ); ?></strong><p>publicações no site</p></div></article>
            <article class="card"><span class="ms">mic_external_on</span><div><small>PRINCIPAL</small><strong><?php echo (int) $principal; ?></strong><p>músicas como artista principal</p></div></article>
            <article class="card"><span class="ms">groups</span><div><small>PARTICIPAÇÕES</small><strong><?php echo (int) $features; ?></strong><p>feats e colaborações</p></div></article>
            <article class="card"><span class="ms">monitoring</span><div><small>ALCANCE NO SITE</small><strong><?php echo esc_html( number_format_i18n( $plays + $downloads ) ); ?></strong><p>reproduções e downloads</p></div></article>
        </section>

        <section class="art-track-catalog card">
            <div class="art-track-catalog-head">
                <div><span class="art-track-eyebrow">PUBLICADO NA 1MZ</span><h3>As tuas músicas</h3><p>O catálogo acompanha automaticamente o Art Track definido pela equipa.</p></div>
                <?php if ( count( $musics ) > 4 ): ?><label class="art-track-search"><span class="ms">search</span><input type="search" placeholder="Pesquisar música" data-art-track-search></label><?php endif; ?>
            </div>

            <?php if ( empty( $musics ) ): ?>
                <div class="art-track-catalog-empty"><span class="ms">music_note</span><h4>O Art Track já está ligado</h4><p>As músicas aparecerão aqui assim que forem publicadas no site.</p></div>
            <?php else: ?>
                <div class="art-track-list" data-art-track-list>
                    <?php foreach ( $musics as $music ):
                        $cover = get_the_post_thumbnail_url( $music->ID, 'medium' );
                        $native_role = $native_available && function_exists( 'rmbz_art_track_music_role' ) ? rmbz_art_track_music_role( $track_id, $music->ID ) : '';
                        $is_primary = $native_role === 'primary' || ( $native_role === '' && (int) get_post_meta( $music->ID, '_imz_artista_id', true ) === $track_id );
                        $music_downloads = (int) get_post_meta( $music->ID, '_imz_download_count', true );
                        $music_plays = function_exists( 'imz_get_play_count' ) ? (int) imz_get_play_count( $music->ID ) : 0;
                    ?>
                        <article class="art-track-song" data-art-track-song data-title="<?php echo esc_attr( wp_strip_all_tags( $music->post_title ) ); ?>">
                            <div class="art-track-song-cover"><?php if ( $cover ): ?><img src="<?php echo esc_url( $cover ); ?>" alt=""><?php else: ?><span class="ms">music_note</span><?php endif; ?></div>
                            <div class="art-track-song-copy"><h4><?php echo esc_html( $music->post_title ); ?></h4><p><?php echo esc_html( get_the_date( 'd/m/Y', $music ) ); ?> · <?php echo $is_primary ? 'Artista principal' : 'Participação'; ?></p></div>
                            <span class="art-track-role <?php echo $is_primary ? 'primary' : 'feat'; ?>"><?php echo $is_primary ? 'Principal' : 'Feat'; ?></span>
                            <div class="art-track-song-stats"><span><span class="ms">play_arrow</span><?php echo esc_html( number_format_i18n( $music_plays ) ); ?></span><span><span class="ms">download</span><?php echo esc_html( number_format_i18n( $music_downloads ) ); ?></span></div>
                            <a class="art-track-open" href="<?php echo esc_url( get_permalink( $music->ID ) ); ?>" target="_blank" rel="noopener"><span class="ms">open_in_new</span><span>Ver no site</span></a>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>
    </div>
    <script>
    (function(){
        var input=document.querySelector('[data-art-track-search]');
        var list=document.querySelector('[data-art-track-list]');
        if(!input||!list)return;
        input.addEventListener('input',function(){
            var query=(input.value||'').trim().toLocaleLowerCase('pt');
            list.querySelectorAll('[data-art-track-song]').forEach(function(row){
                var title=(row.getAttribute('data-title')||'').toLocaleLowerCase('pt');
                row.hidden=query!==''&&title.indexOf(query)===-1;
            });
        });
    })();
    </script>
    <?php
    return ob_get_clean();
}
