<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-scoped local variables.
$post_id  = $post->ID;
$status   = get_post_meta( $post_id, '_falcify_status', true );
$last     = get_post_meta( $post_id, '_falcify_last_generated_at', true );
$wc       = (int) get_post_meta( $post_id, '_falcify_word_count', true );
$content  = (string) get_post_meta( $post_id, '_falcify_content', true );
$pictos   = (string) get_post_meta( $post_id, '_falcify_content_pictos', true );
$enabled  = Falcify_Post_Types::is_enabled( $post->post_type );
$opts_p   = Falcify_Settings::get();

// Texte original lisible (privé du HTML de Gutenberg).
$original_raw  = wp_strip_all_tags( do_blocks( (string) $post->post_content ) );
$original_text = trim( preg_replace( '/\s+/', ' ', $original_raw ) );

// Map des statuts → libellé "humain" + couleur.
$state_meta = array(
    ''          => array( 'label' => __( 'Non généré', 'falcify-connector' ),  'pill' => 'falcify-pill-info',  'step' => 0 ),
    'draft'     => array( 'label' => __( 'À vérifier', 'falcify-connector' ),  'pill' => 'falcify-pill-warn',  'step' => 1 ),
    'validated' => array( 'label' => __( 'Conforme FALC', 'falcify-connector' ), 'pill' => 'falcify-pill-ok',  'step' => 2 ),
    'published' => array( 'label' => __( 'Publié', 'falcify-connector' ),       'pill' => 'falcify-pill-ok',  'step' => 3 ),
);
$state    = isset( $state_meta[ $status ] ) ? $state_meta[ $status ] : $state_meta[''];
$has_falc = $content !== '';
$state_attr = $has_falc ? ( $status ?: 'draft' ) : 'idle-empty';

// Étapes du workflow.
$steps = array(
    1 => __( 'Générer', 'falcify-connector' ),
    2 => __( 'Vérifier', 'falcify-connector' ),
    3 => __( 'Publier', 'falcify-connector' ),
);
$active_step = 1;
if ( $has_falc ) {
    if ( $status === 'published' || $status === 'validated' ) $active_step = 3;
    else $active_step = 2;
}

$editor_id      = 'falcify_content_' . $post_id;
$editor_content = ( $pictos !== '' ) ? $pictos : $content;
?>
<div class="falcify-metabox falcify-card-v2" data-post-id="<?php echo esc_attr( $post_id ); ?>" data-mode="strict" data-state="<?php echo esc_attr( $state_attr ); ?>">
    <?php wp_nonce_field( 'falcify_metabox_save_' . $post_id, 'falcify_metabox_nonce' ); ?>

    <?php if ( ! $enabled ): ?>
        <p class="falcify-warn">
            <?php esc_html_e( 'Ce type de contenu n\'est pas activé pour Falcify.', 'falcify-connector' ); ?>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=falcify-connector&tab=settings' ) ); ?>"><?php esc_html_e( 'Activer dans les paramètres', 'falcify-connector' ); ?></a>
        </p>
    <?php endif; ?>

    <!-- HEADER : statut · score · dernière maj -->
    <header class="falcify-card-header">
        <div class="falcify-header-left">
            <span class="falcify-pill <?php echo esc_attr( $state['pill'] ); ?>" data-falcify-status-pill>
                <span class="falcify-dot"></span>
                <?php echo esc_html( $state['label'] ); ?>
            </span>
            <?php if ( $has_falc ): ?>
                <span class="falcify-score" data-falcify-score title="<?php esc_attr_e( 'Score de lisibilité estimé', 'falcify-connector' ); ?>">
                    <span class="falcify-score-value">—</span><span class="falcify-score-max">/100</span>
                </span>
            <?php endif; ?>
        </div>
        <div class="falcify-header-right falcify-muted">
            <?php if ( $last ): ?>
                <span><?php
                    /* translators: %s: date */
                    printf( esc_html__( 'Dernière mise à jour : %s', 'falcify-connector' ), esc_html( $last ) );
                ?></span>
            <?php endif; ?>
            <?php if ( $wc ): ?>
                <span>· <?php
                    /* translators: %s: word count */
                    printf( esc_html__( '%s mots', 'falcify-connector' ), esc_html( number_format_i18n( $wc ) ) );
                ?></span>
            <?php endif; ?>
        </div>
    </header>

    <!-- WORKFLOW : 3 étapes -->
    <ol class="falcify-stepper" aria-label="<?php esc_attr_e( 'Étapes', 'falcify-connector' ); ?>">
        <?php foreach ( $steps as $n => $label ):
            $is_active = ( $n === $active_step );
            $is_done   = ( $n < $active_step );
            $cls = $is_active ? 'is-active' : ( $is_done ? 'is-done' : '' );
        ?>
            <li class="falcify-stepper-item <?php echo esc_attr( $cls ); ?>">
                <span class="falcify-stepper-num"><?php echo $is_done ? '✓' : esc_html( (string) $n ); ?></span>
                <span class="falcify-stepper-label"><?php echo esc_html( $label ); ?></span>
            </li>
        <?php endforeach; ?>
    </ol>

    <!-- BODY : split view original / version facile -->
    <div class="falcify-split">
        <section class="falcify-split-pane falcify-split-left" aria-labelledby="falcify-pane-orig-<?php echo esc_attr( $post_id ); ?>">
            <header class="falcify-split-head">
                <h4 id="falcify-pane-orig-<?php echo esc_attr( $post_id ); ?>"><?php esc_html_e( 'Texte original', 'falcify-connector' ); ?></h4>
                <span class="falcify-muted"><?php esc_html_e( 'Lecture seule', 'falcify-connector' ); ?></span>
            </header>
            <div class="falcify-original" data-falcify-original><?php echo esc_html( $original_text ?: __( '(Cette page n\'a pas encore de contenu.)', 'falcify-connector' ) ); ?></div>
        </section>

        <section class="falcify-split-pane falcify-split-right" aria-labelledby="falcify-pane-easy-<?php echo esc_attr( $post_id ); ?>">
            <header class="falcify-split-head">
                <h4 id="falcify-pane-easy-<?php echo esc_attr( $post_id ); ?>"><?php esc_html_e( 'Version facile à lire', 'falcify-connector' ); ?></h4>
                <span class="falcify-muted"><?php esc_html_e( 'Modifiable', 'falcify-connector' ); ?></span>
            </header>
            <?php if ( ! $has_falc ): ?>
                <div class="falcify-empty-pane">
                    <p>📝 <?php esc_html_e( 'Pas encore de version facile à lire.', 'falcify-connector' ); ?></p>
                    <p class="falcify-muted"><?php esc_html_e( 'Cliquez sur le bouton ci-dessous pour la générer.', 'falcify-connector' ); ?></p>
                </div>
            <?php endif; ?>
            <div class="falcify-editor-wrap" <?php if ( ! $has_falc ): ?>hidden<?php endif; ?>>
                <?php
                wp_editor(
                    $editor_content,
                    $editor_id,
                    array(
                        'textarea_name' => $editor_id,
                        'media_buttons' => false,
                        'textarea_rows' => 12,
                        'teeny'         => true,
                        'tinymce'       => array(
                            'toolbar1'      => 'formatselect,bold,italic,underline,bullist,numlist,link,unlink,removeformat,undo,redo',
                            'toolbar2'      => '',
                            'block_formats' => 'Paragraphe=p;Titre 2=h2;Titre 3=h3',
                        ),
                        'quicktags'     => false,
                    )
                );
                ?>
            </div>
        </section>
    </div>

    <!-- ACTION PRIMAIRE -->
    <div class="falcify-actions falcify-actions-primary">
        <button type="button" class="button button-primary button-hero falcify-btn-generate falcify-action-primary">
            <span aria-hidden="true">⚡</span>
            <?php echo $has_falc
                ? esc_html__( 'Réécrire simplement', 'falcify-connector' )
                : esc_html__( 'Générer la version facile à lire', 'falcify-connector' ); ?>
        </button>
    </div>

    <!-- ACTIONS SECONDAIRES -->
    <?php if ( $has_falc ): ?>
        <div class="falcify-actions falcify-actions-secondary">
            <button type="button" class="button falcify-btn-save" data-editor-id="<?php echo esc_attr( $editor_id ); ?>">
                💾 <?php esc_html_e( 'Enregistrer mes modifications', 'falcify-connector' ); ?>
            </button>
            <button type="button" class="button falcify-btn-open-picker" data-editor-id="<?php echo esc_attr( $editor_id ); ?>">
                ➕🖼️ <?php esc_html_e( 'Insérer un picto', 'falcify-connector' ); ?>
            </button>
            <button type="button" class="button falcify-btn-copy">
                📋 <?php esc_html_e( 'Copier le texte', 'falcify-connector' ); ?>
            </button>

            <?php if ( $status !== 'validated' && $status !== 'published' ): ?>
                <button type="button" class="button falcify-btn-set-status" data-status="validated">
                    ✓ <?php esc_html_e( 'Marquer comme vérifié', 'falcify-connector' ); ?>
                </button>
            <?php endif; ?>
            <?php if ( $status !== 'published' ): ?>
                <button type="button" class="button button-primary falcify-btn-set-status" data-status="published">
                    🌍 <?php esc_html_e( 'Publier sur le site', 'falcify-connector' ); ?>
                </button>
            <?php else: ?>
                <button type="button" class="button falcify-btn-set-status" data-status="draft">
                    ↩ <?php esc_html_e( 'Repasser en brouillon', 'falcify-connector' ); ?>
                </button>
            <?php endif; ?>
        </div>
        <p class="falcify-muted falcify-help">
            <?php esc_html_e( 'Tant que la version n\'est pas publiée, le bouton « Lire facilement » n\'apparaît pas sur le site.', 'falcify-connector' ); ?>
        </p>
    <?php endif; ?>

    <div class="falcify-result" hidden></div>

    <?php // ===== Modale "Banque de pictogrammes" — insertion manuelle dans l'éditeur =====
    if ( $has_falc ): ?>
    <dialog class="falcify-picker-modal" data-falcify-picker-modal data-editor-id="<?php echo esc_attr( $editor_id ); ?>">
        <div class="falcify-picker-inner">
            <header class="falcify-modal-head">
                <h3>🖼️ <?php esc_html_e( 'Banque de pictogrammes', 'falcify-connector' ); ?></h3>
                <button type="button" class="falcify-modal-close" data-picker-close aria-label="<?php esc_attr_e( 'Fermer', 'falcify-connector' ); ?>">×</button>
            </header>
            <p class="falcify-muted falcify-picker-help">
                <?php esc_html_e( 'Cliquez sur un pictogramme pour l\'insérer à l\'endroit du curseur dans l\'éditeur facile à lire.', 'falcify-connector' ); ?>
            </p>
            <div class="falcify-picker-search-wrap">
                <input type="search" class="falcify-picker-search" data-falcify-picker-search placeholder="<?php esc_attr_e( 'Rechercher un pictogramme…', 'falcify-connector' ); ?>" autocomplete="off" />
                <span class="falcify-picker-count" data-falcify-picker-count></span>
            </div>
            <div class="falcify-picker-grid" data-falcify-picker-grid role="list"></div>
            <div class="falcify-picker-empty" data-falcify-picker-empty hidden><?php esc_html_e( 'Aucun pictogramme ne correspond.', 'falcify-connector' ); ?></div>
            <div class="falcify-modal-actions">
                <button type="button" class="button" data-picker-close><?php esc_html_e( 'Fermer', 'falcify-connector' ); ?></button>
            </div>
        </div>
    </dialog>
    <?php endif; ?>

</div>
