<?php
/**
 * 1MZ For Artists — Design System
 * includes/design-system.php — Helpers PHP para componentes
 *
 * Estes helpers geram HTML consistente para os componentes do design
 * system. Em vez de copiar/colar HTML em cada modal, botão e card,
 * usar estas funções:
 *
 *   echo rmbz_btn(['label' => 'Levantar', 'variant' => 'primary']);
 *   echo rmbz_modal(['id' => 'wd', 'title' => '...', 'body' => '...']);
 *
 * Todos os helpers fazem escape automático e devolvem string (não echo).
 */

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

/**
 * ============================================================================
 * ENQUEUE — carregar tokens, base, components e JS do design system
 * ============================================================================
 *
 * Chamar UMA vez em qualquer página onde o plugin renderize algo. As funções
 * existentes (rmbz_enqueue_scripts) podem invocar isto antes do CSS específico
 * da página.
 */
function rmbz_enqueue_design_system() {
    static $loaded = false;
    if ( $loaded ) return;
    $loaded = true;

    $url = RMBZ_PLUGIN_URL . 'assets/';
    $ver = defined( 'RMBZ_PLUGIN_VERSION' ) ? RMBZ_PLUGIN_VERSION : '1.0';

    // Google Fonts — Bricolage Grotesque + Geist + JetBrains Mono
    wp_enqueue_style(
        'rmbz-fonts',
        'https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,400;12..96,500;12..96,600;12..96,700&family=Geist:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap',
        [],
        null
    );

    wp_enqueue_style( 'rmbz-ds-tokens',     $url . 'css/01-tokens.css',     [],                  $ver );
    wp_enqueue_style( 'rmbz-ds-base',       $url . 'css/02-base.css',       ['rmbz-ds-tokens'],  $ver );
    wp_enqueue_style( 'rmbz-ds-components', $url . 'css/03-components.css', ['rmbz-ds-base'],    $ver );

    // [1.5.118] Theme shield para componentes do Design System (notificações,
    // FDG, modais, toasts, popups, intro-welcome, gate cards, alerts).
    // Carrega POR ÚLTIMO no DS para neutralizar regras agressivas do tema
    // dentro destes containers em qualquer página onde apareçam.
    wp_enqueue_style( 'rmbz-ds-theme-shield', $url . 'css/ds-theme-shield.css', ['rmbz-ds-components'], $ver );

    wp_enqueue_script( 'rmbz-ds-js', $url . 'js/design-system.js', [], $ver, true );
}


/**
 * ============================================================================
 * BUTTON
 * ============================================================================
 *
 * @param array $args {
 *   @type string $label    Texto do botão (escaped)
 *   @type string $variant  primary|ghost|outline|danger|success|icon  (default: primary)
 *   @type string $size     sm|md|lg                                   (default: md)
 *   @type string $icon     Emoji ou HTML pequeno (NÃO escaped — confia no caller)
 *   @type string $type     button|submit|reset                        (default: button)
 *   @type string $href     Se presente, vira <a>
 *   @type bool   $full     Largura 100%
 *   @type bool   $loading  Estado loading inicial
 *   @type array  $attrs    data-*, aria-*, id, name, etc
 * }
 * @return string HTML do botão
 */
function rmbz_btn( array $args = [] ) : string {
    $a = wp_parse_args( $args, [
        'label'   => '',
        'variant' => 'primary',
        'size'    => 'md',
        'icon'    => '',
        'type'    => 'button',
        'href'    => '',
        'full'    => false,
        'loading' => false,
        'attrs'   => [],
    ] );

    $tag = ! empty( $a['href'] ) ? 'a' : 'button';

    $classes = [ 'rmbz-btn' ];
    $classes[] = 'rmbz-btn--' . sanitize_html_class( $a['variant'] );
    if ( $a['size'] !== 'md' ) {
        $classes[] = 'rmbz-btn--' . sanitize_html_class( $a['size'] );
    }
    if ( $a['full'] )    $classes[] = 'rmbz-btn--full';
    if ( $a['loading'] ) $classes[] = 'rmbz-btn--loading';

    $attrs_str = '';
    foreach ( $a['attrs'] as $k => $v ) {
        $attrs_str .= ' ' . esc_attr( $k ) . '="' . esc_attr( $v ) . '"';
    }
    if ( $tag === 'a' ) {
        $attrs_str .= ' href="' . esc_url( $a['href'] ) . '"';
    } else {
        $attrs_str .= ' type="' . esc_attr( $a['type'] ) . '"';
    }

    $icon_html = '';
    if ( ! empty( $a['icon'] ) ) {
        // Aceita emoji ou SVG/HTML — caller é responsável por escape se for SVG
        $icon_html = '<span class="rmbz-btn__icon" aria-hidden="true">' . $a['icon'] . '</span>';
    }

    $label_html = '<span>' . esc_html( $a['label'] ) . '</span>';

    return sprintf(
        '<%1$s class="%2$s"%3$s>%4$s%5$s</%1$s>',
        $tag,
        esc_attr( implode( ' ', $classes ) ),
        $attrs_str,
        $icon_html,
        $label_html
    );
}


/**
 * ============================================================================
 * INPUT FIELD — wrapper com label, hint, error
 * ============================================================================
 *
 * @param array $args {
 *   @type string $name        REQUIRED
 *   @type string $label       (vazio = sem label visível)
 *   @type string $type        text|email|tel|number|password|date  (default: text)
 *   @type string $value       Valor inicial
 *   @type string $placeholder
 *   @type string $hint        Texto de ajuda em baixo
 *   @type string $error       Se presente, mostra estado de erro
 *   @type bool   $required
 *   @type string $id          Default: gera de $name
 *   @type array  $attrs       Atributos extra no <input>
 *   @type string $prefix      Texto antes do input (cria input-group)
 *   @type string $suffix      Texto depois do input (cria input-group)
 *   @type string $variant     '' | 'money'                          (default: '')
 * }
 */
function rmbz_field( array $args = [] ) : string {
    $a = wp_parse_args( $args, [
        'name'        => '',
        'label'       => '',
        'type'        => 'text',
        'value'       => '',
        'placeholder' => '',
        'hint'        => '',
        'error'       => '',
        'required'    => false,
        'id'          => '',
        'attrs'       => [],
        'prefix'      => '',
        'suffix'      => '',
        'variant'     => '',
    ] );

    if ( empty( $a['name'] ) ) return '';
    if ( empty( $a['id'] ) )   $a['id'] = 'rmbz-' . sanitize_html_class( $a['name'] );

    // [DS 1.5.35] Se vier 'id' nos attrs, dá-lhe prioridade sobre o id default
    // (o caller pediu explicitamente). Isto evita que o <input> saia com DOIS
    // atributos id="" — bug que tornava document.getElementById() inútil.
    if ( isset( $a['attrs']['id'] ) && ! empty( $a['attrs']['id'] ) ) {
        $a['id'] = $a['attrs']['id'];
        unset( $a['attrs']['id'] );
    }

    $field_classes = [ 'rmbz-field' ];
    if ( ! empty( $a['error'] ) ) $field_classes[] = 'rmbz-field--error';

    $input_classes = [ 'rmbz-input' ];
    if ( $a['variant'] === 'money' ) $input_classes[] = 'rmbz-input--money';

    $attrs_str = '';
    foreach ( $a['attrs'] as $k => $v ) {
        $attrs_str .= ' ' . esc_attr( $k ) . '="' . esc_attr( $v ) . '"';
    }
    if ( $a['required'] ) $attrs_str .= ' required';
    if ( ! empty( $a['placeholder'] ) ) {
        $attrs_str .= ' placeholder="' . esc_attr( $a['placeholder'] ) . '"';
    }

    $input_html = sprintf(
        '<input class="%1$s" type="%2$s" name="%3$s" id="%4$s" value="%5$s"%6$s />',
        esc_attr( implode( ' ', $input_classes ) ),
        esc_attr( $a['type'] ),
        esc_attr( $a['name'] ),
        esc_attr( $a['id'] ),
        esc_attr( $a['value'] ),
        $attrs_str
    );

    // Se há prefix/suffix, embrulhar em input-group
    if ( ! empty( $a['prefix'] ) || ! empty( $a['suffix'] ) ) {
        $group  = '<div class="rmbz-input-group">';
        if ( $a['prefix'] ) {
            $group .= '<span class="rmbz-input-group__addon">' . esc_html( $a['prefix'] ) . '</span>';
        }
        $group .= $input_html;
        if ( $a['suffix'] ) {
            $group .= '<span class="rmbz-input-group__addon rmbz-input-group__addon--right">' . esc_html( $a['suffix'] ) . '</span>';
        }
        $group .= '</div>';
        $input_html = $group;
    }

    $label_html = $a['label']
        ? '<label class="rmbz-field__label" for="' . esc_attr( $a['id'] ) . '">' . esc_html( $a['label'] ) . '</label>'
        : '';

    $hint_html = $a['hint']
        ? '<span class="rmbz-field__hint">' . esc_html( $a['hint'] ) . '</span>'
        : '';

    $error_html = $a['error']
        ? '<span class="rmbz-field__error" role="alert">⚠ ' . esc_html( $a['error'] ) . '</span>'
        : '';

    return sprintf(
        '<div class="%1$s">%2$s%3$s%4$s%5$s</div>',
        esc_attr( implode( ' ', $field_classes ) ),
        $label_html,
        $input_html,
        $hint_html,
        $error_html
    );
}


/**
 * ============================================================================
 * MODAL — sistema único partilhado
 * ============================================================================
 *
 * @param array $args {
 *   @type string $id      REQUIRED — ID único
 *   @type string $title   Título no header (escaped)
 *   @type string $body    HTML do conteúdo (NÃO escaped — caller é responsável)
 *   @type string $footer  HTML opcional dos botões
 *   @type string $size    sm|md|lg                  (default: md)
 *   @type bool   $closable Mostra botão × no header (default: true)
 * }
 */
function rmbz_modal( array $args = [] ) : string {
    $a = wp_parse_args( $args, [
        'id'       => '',
        'title'    => '',
        'body'     => '',
        'footer'   => '',
        'size'     => 'md',
        'closable' => true,
    ] );

    if ( empty( $a['id'] ) ) return '';

    $classes = [ 'rmbz-modal' ];
    if ( $a['size'] !== 'md' ) $classes[] = 'rmbz-modal--' . sanitize_html_class( $a['size'] );

    $close_btn = '';
    if ( $a['closable'] ) {
        // [DS 1.5.33] × via SVG inline — sobrevive a overrides de font-size do
        // tema do utilizador. Visual idêntico em qualquer ambiente.
        $close_icon_svg = '<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M14 4L4 14M4 4L14 14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
        $close_btn = sprintf(
            '<button type="button" class="rmbz-btn rmbz-btn--icon rmbz-modal__close" data-rmbz-action="close" aria-label="%s">%s</button>',
            esc_attr__( 'Fechar', '1mz-for-artists' ),
            $close_icon_svg
        );
    }

    $title_html = $a['title']
        ? '<h3 class="rmbz-modal__title" id="' . esc_attr( $a['id'] ) . '-title">' . esc_html( $a['title'] ) . '</h3>'
        : '<span></span>';

    $header_html = '';
    if ( $a['title'] || $a['closable'] ) {
        $header_html = '<header class="rmbz-modal__header">' . $title_html . $close_btn . '</header>';
    }

    $footer_html = $a['footer']
        ? '<footer class="rmbz-modal__footer">' . $a['footer'] . '</footer>'
        : '';

    return sprintf(
        '<div class="%1$s" id="%2$s" data-rmbz-modal hidden>
            <div class="rmbz-modal__overlay" data-rmbz-action="close" tabindex="-1"></div>
            <div class="rmbz-modal__panel" role="dialog" aria-modal="true" aria-labelledby="%2$s-title">
                %3$s
                <div class="rmbz-modal__body">%4$s</div>
                %5$s
            </div>
        </div>',
        esc_attr( implode( ' ', $classes ) ),
        esc_attr( $a['id'] ),
        $header_html,
        $a['body'],
        $footer_html
    );
}


/**
 * ============================================================================
 * STAT CARD
 * ============================================================================
 *
 * @param array $args {
 *   @type string $label   Eyebrow (ex: "Saldo Carteira")
 *   @type string $amount  Número (já formatado: "1.250,00")
 *   @type string $unit    Unidade (ex: "MT", "USD")
 *   @type string $trend   Texto da tendência (ex: "+12% este mês")
 *   @type string $trend_direction  up|down|flat
 *   @type string $variant default|brand
 *   @type string $action_label  Label do botão de acção
 *   @type string $action_modal  ID do modal a abrir
 *   @type string $icon
 * }
 */
function rmbz_stat( array $args = [] ) : string {
    $a = wp_parse_args( $args, [
        'label'           => '',
        'amount'          => '',
        'unit'            => '',
        'trend'           => '',
        'trend_direction' => 'flat',
        'variant'         => 'default',
        'action_label'    => '',
        'action_modal'    => '',
        'icon'            => '',
    ] );

    $classes = [ 'rmbz-stat' ];
    if ( $a['variant'] === 'brand' ) $classes[] = 'rmbz-stat--brand';

    $trend_html = '';
    if ( $a['trend'] ) {
        $arrow = ['up' => '↑', 'down' => '↓', 'flat' => '→'][ $a['trend_direction'] ] ?? '';
        $trend_html = sprintf(
            '<span class="rmbz-stat__trend rmbz-stat__trend--%s">%s %s</span>',
            esc_attr( $a['trend_direction'] ),
            esc_html( $arrow ),
            esc_html( $a['trend'] )
        );
    }

    $action_html = '';
    if ( $a['action_label'] && $a['action_modal'] ) {
        $action_html = '<div class="rmbz-stat__action">' . rmbz_btn( [
            'label'   => $a['action_label'],
            'variant' => 'outline',
            'size'    => 'sm',
            'attrs'   => [ 'data-rmbz-modal-open' => $a['action_modal'] ],
        ] ) . '</div>';
    }

    return sprintf(
        '<div class="%1$s">
            <span class="rmbz-stat__label">%2$s</span>
            <div class="rmbz-stat__value">
                <span class="rmbz-stat__amount">%3$s</span>
                %4$s
            </div>
            %5$s
            %6$s
        </div>',
        esc_attr( implode( ' ', $classes ) ),
        esc_html( $a['label'] ),
        esc_html( $a['amount'] ),
        $a['unit'] ? '<span class="rmbz-stat__unit">' . esc_html( $a['unit'] ) . '</span>' : '',
        $trend_html,
        $action_html
    );
}


/**
 * ============================================================================
 * BADGE
 * ============================================================================
 */
function rmbz_badge( string $label, string $variant = 'neutral', string $icon = '' ) : string {
    $valid = [ 'neutral', 'brand', 'success', 'danger', 'warning', 'info', 'vip' ];
    if ( ! in_array( $variant, $valid, true ) ) $variant = 'neutral';

    return sprintf(
        '<span class="rmbz-badge rmbz-badge--%s">%s%s</span>',
        esc_attr( $variant ),
        $icon ? '<span aria-hidden="true">' . $icon . '</span>' : '',
        esc_html( $label )
    );
}


/**
 * ============================================================================
 * ALERT (banner inline)
 * ============================================================================
 */
function rmbz_alert( array $args = [] ) : string {
    $a = wp_parse_args( $args, [
        'variant' => 'info',  // info|success|danger|warning
        'title'   => '',
        'body'    => '',
        'icon'    => '',
    ] );

    $icons = [ 'info' => 'ℹ', 'success' => '✓', 'danger' => '✕', 'warning' => '⚠' ];
    $icon  = $a['icon'] ?: ( $icons[ $a['variant'] ] ?? '•' );

    $title_html = $a['title']
        ? '<div class="rmbz-alert__title">' . esc_html( $a['title'] ) . '</div>'
        : '';

    return sprintf(
        '<div class="rmbz-alert rmbz-alert--%s" role="%s">
            <span class="rmbz-alert__icon" aria-hidden="true">%s</span>
            <div class="rmbz-alert__body">%s%s</div>
        </div>',
        esc_attr( $a['variant'] ),
        $a['variant'] === 'danger' ? 'alert' : 'status',
        $icon, // [1.5.119] Aceita SVG/HTML como ícone — caller responsável por escape
               // (alinhado com rmbz_btn). Todos os callers actuais passam constantes
               // definidas no código (variáveis $icon_* ou emojis literais), nunca
               // input do utilizador. Antes desta correcção, esc_html() convertia
               // SVG cru para texto literal, partindo o componente.
        $title_html,
        $a['body']  // permite HTML no body — caller responsável por escape
    );
}


/**
 * ============================================================================
 * EMPTY STATE
 * ============================================================================
 */
function rmbz_empty_state( array $args = [] ) : string {
    $a = wp_parse_args( $args, [
        'icon'        => '∅',
        'title'       => __( 'Sem resultados', '1mz-for-artists' ),
        'description' => '',
        'action'      => '',  // HTML do botão (use rmbz_btn)
    ] );

    return sprintf(
        '<div class="rmbz-empty">
            <div class="rmbz-empty__icon" aria-hidden="true">%s</div>
            <h4 class="rmbz-empty__title">%s</h4>
            %s
            %s
        </div>',
        $a['icon'], // [1.5.119] Aceita SVG/HTML — caller responsável por escape
                    // (alinhado com rmbz_btn e rmbz_alert).
        esc_html( $a['title'] ),
        $a['description'] ? '<p class="rmbz-empty__description">' . esc_html( $a['description'] ) . '</p>' : '',
        $a['action']  // HTML do botão
    );
}


/**
 * ============================================================================
 * PILL GROUP — toggle entre opções
 *
 * @param array $args {
 *   @type string $name      Identificador semântico (não obrigatório)
 *   @type array  $options   [ ['value'=>'wallet','label'=>'Carteira','target'=>'wd-wallet','active'=>true], ... ]
 *   @type bool   $full      Esticar largura
 * }
 */
function rmbz_pill_group( array $args = [] ) : string {
    $a = wp_parse_args( $args, [
        'name'    => '',
        'options' => [],
        'full'    => false,
    ] );

    if ( empty( $a['options'] ) ) return '';

    $classes = [ 'rmbz-pill-group' ];
    if ( $a['full'] ) $classes[] = 'rmbz-pill-group--full';

    $pills = '';
    foreach ( $a['options'] as $opt ) {
        $opt = wp_parse_args( $opt, [
            'value'  => '',
            'label'  => '',
            'target' => '',
            'active' => false,
            'icon'   => '',
        ] );

        $cls = 'rmbz-pill';
        if ( $opt['active'] ) $cls .= ' is-active';

        $attrs = sprintf(
            'data-rmbz-pill data-value="%s"%s aria-selected="%s"',
            esc_attr( $opt['value'] ),
            $opt['target'] ? ' data-target="' . esc_attr( $opt['target'] ) . '"' : '',
            $opt['active'] ? 'true' : 'false'
        );

        $icon = $opt['icon'] ? '<span aria-hidden="true">' . $opt['icon'] . '</span>' : '';

        $pills .= sprintf(
            '<button type="button" class="%s" role="tab" %s>%s%s</button>',
            esc_attr( $cls ),
            $attrs,
            $icon,
            esc_html( $opt['label'] )
        );
    }

    return sprintf(
        '<div class="%s" role="tablist" data-rmbz-pill-group%s>%s</div>',
        esc_attr( implode( ' ', $classes ) ),
        $a['name'] ? ' aria-label="' . esc_attr( $a['name'] ) . '"' : '',
        $pills
    );
}


/**
 * ============================================================================
 * APP WRAPPER — embrulha conteúdo do plugin para activar o design system
 *
 * Uso: echo rmbz_app_open(); ... echo rmbz_app_close();
 *      ou: rmbz_app(function() { ... }); para closure pattern
 * ============================================================================
 */
function rmbz_app_open( string $extra_class = '' ) : string {
    $cls = 'rmbz-app' . ( $extra_class ? ' ' . sanitize_html_class( $extra_class ) : '' );
    return '<div class="' . esc_attr( $cls ) . '">';
}

function rmbz_app_close() : string {
    return '</div>';
}
