<?php
/**
 * Edit screen language badge for translation management.
 *
 * @package WPR_Translate
 */

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

/**
 * Appends the language badge to the edit screen heading.
 */
function wpr_translation_render_edit_screen_language_badge() {
    // Read the current screen to ensure this is a post editor view.
    $screen = get_current_screen();

    if ( ! $screen || 'post' !== $screen->base ) {
        return;
    }

    // Determine the current post and its language code.
    $post_id       = isset( $_GET['post'] ) ? absint( $_GET['post'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $language_code = '';

    if ( $post_id ) {
        $post = get_post( $post_id );

        if ( ! $post ) {
            return;
        }

        // Resolve the language assigned to this post.
        $language_code = wpr_translation_resolve_post_language_code( $post_id, $post->post_type );
    }

    if ( '' === $language_code ) {
        // Fall back to the default language setting.
        $default_language = wpr_translate_get_default_language();

        if ( null !== $default_language && ! empty( $default_language['code'] ) ) {
            $language_code = $default_language['code'];
        }
    }

    if ( '' === $language_code ) {
        // Final fallback to the first active language.
        $languages = wpr_translation_get_active_languages();

        if ( ! empty( $languages ) ) {
            $language_code = wpr_translation_get_default_language_code( $languages );
        }
    }

    if ( '' === $language_code ) {
        // No language could be resolved.
        return;
    }

    if ( $post_id ) {
        // Use the "version" label for existing posts.
        $label = wpr_translation_format_language_version_label( $language_code );
    } else {
        // Use the "creation" label for new posts.
        $label = wpr_translation_format_language_creation_label( $language_code );
    }

    if ( '' === $label ) {
        // No label to display.
        return;
    }

    $language_name = '';
    $flag_code     = '';

    if ( function_exists( 'wpr_translate_get_language' ) ) {
        // Retrieve the language metadata for name/flag.
        $language_data = wpr_translate_get_language( $language_code );

        if ( is_array( $language_data ) ) {
            if ( ! empty( $language_data['name'] ) ) {
                $language_name = sanitize_text_field( $language_data['name'] );
            }

            if ( ! empty( $language_data['flag'] ) ) {
                $flag_code = sanitize_key( $language_data['flag'] );
            }
        }
    }

    if ( '' === $flag_code && '' !== $language_code ) {
        // Fall back to the language code when no explicit flag was assigned in the settings.
        $flag_code = sanitize_key( $language_code );
    }

    $flag_url = '';

    if ( '' !== $flag_code && defined( 'WPR_TRANSLATE_URL' ) ) {
        // Build the flag URL from the plugin assets.
        $flag_url = esc_url_raw( WPR_TRANSLATE_URL . 'assets/img/flags/4x3/' . $flag_code . '.svg' );
    }

    if ( '' === $language_name ) {
        // Fall back to the uppercase code as a label.
        $language_name = strtoupper( $language_code );
    }

    if ( '' !== $language_name ) {
        /* translators: %s: Language name. */
        $flag_alt = sprintf( __( '%s flag', 'wpr-translate' ), $language_name );
    } else {
        $flag_alt = __( 'Language flag', 'wpr-translate' );
    }

    $badge_data = array(
        'label'   => sanitize_text_field( $label ),
        'flagUrl' => $flag_url,
        'flagAlt' => sanitize_text_field( $flag_alt ),
    );

    // Inject minimal styles and a script to append the badge after DOM ready.
    echo '<style>.wpr-translation-heading-language{display:inline-flex;align-items:center;gap:6px;margin-left:8px;font-size:14px;font-weight:400;color:#555;}.wpr-translation-heading-language img{width:18px;height:14px;border-radius:2px;box-shadow:0 0 0 1px rgba(0,0,0,0.08);object-fit:cover;}</style>';
    printf(
        '<script>document.addEventListener("DOMContentLoaded",function(){var heading=document.querySelector(".wrap > h1.wp-heading-inline");if(!heading){return;}var badgeData=%s;if(!badgeData||!badgeData.label){return;}var badge=document.createElement("span");badge.className="wpr-translation-heading-language";if(badgeData.flagUrl){var flag=document.createElement("img");flag.src=badgeData.flagUrl;flag.alt=badgeData.flagAlt||"";flag.loading="lazy";flag.decoding="async";badge.appendChild(flag);}badge.appendChild(document.createTextNode(badgeData.label));heading.appendChild(document.createTextNode(" "));heading.appendChild(badge);});</script>',
        wp_json_encode( $badge_data )
    );
}
