<?php
/**
 * Chatbot Embed Template
 *
 * Uses chatbot-preview.css for styling with SVG icons.
 * Supports both widget (popup) and inline (shortcode) modes.
 *
 * Variables available:
 * - $chatbot: Chatbot object with id, name, config
 * - $config: Parsed config array
 * - $mode: 'widget' or 'inline'
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/public/partials
 */

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

// Extract appearance settings with defaults
$appearance = $config['appearance'] ?? array();
$behavior   = $config['behavior'] ?? array();
$deployment = $config['deployment'] ?? array();

$primary_color       = $appearance['primaryColor'] ?? '#3B82F6';
$theme_mode          = $appearance['mode'] ?? 'light';
$bubble_style        = $appearance['bubbleStyle'] ?? 'rounded';
$animations          = $appearance['animations'] ?? true;
$avatar              = $chatbot->avatar ?? 'chat';
$widget_position     = sanitize_key($deployment['widgetPosition'] ?? 'bottom-right');

$welcome_message     = $behavior['welcomeMessage'] ?? __('Hi! How can I help you today?', 'kitsune-ai-platform');
$suggested_questions = $behavior['suggestedQuestions'] ?? array();
$suggestions_trigger = sanitize_key($behavior['suggestedQuestionsTrigger'] ?? 'immediate');

// Build CSS classes
$widget_classes = array('chatbot-preview');
$widget_classes[] = 'chatbot-preview--' . ($theme_mode === 'dark' ? 'dark' : 'light');
$widget_classes[] = 'chatbot-preview--bubble-' . esc_attr($bubble_style);
if ($animations) {
    $widget_classes[] = 'chatbot-preview--animated';
}

// Avatar URL resolution
$avatar_value = is_scalar($avatar) ? trim((string) $avatar) : 'chat';
$legacy_avatar_map = array(
    'ChatDotRound' => 'chat',
    'CustomChat' => 'chat',
    'Service' => 'service',
    'CustomService' => 'service',
    'Cpu' => 'ai',
    'CustomAI' => 'ai',
);

if (isset($legacy_avatar_map[$avatar_value])) {
    $avatar_value = $legacy_avatar_map[$avatar_value];
}

$icon_url_map = array(
    'chat' => KITSUNE_AI_PLATFORM_PLUGIN_URL . 'public/assets/icon/chat.svg',
    'service' => KITSUNE_AI_PLATFORM_PLUGIN_URL . 'public/assets/icon/service.svg',
    'ai' => KITSUNE_AI_PLATFORM_PLUGIN_URL . 'public/assets/icon/ai.svg',
);

$uploads = wp_upload_dir();
$allowed_upload_base = trailingslashit($uploads['baseurl']) . 'ai-platform/chatbot-avatars/';
$avatar_url = '';

if (is_string($avatar_value) && strpos($avatar_value, 'http') === 0 && strpos($avatar_value, $allowed_upload_base) === 0) {
    $avatar_url = esc_url_raw($avatar_value);
} elseif (isset($icon_url_map[$avatar_value])) {
    $avatar_url = esc_url_raw($icon_url_map[$avatar_value]);
} else {
    $avatar_url = esc_url_raw($icon_url_map['chat']);
}

$svg_allowed_tags = array(
    'svg' => array(
        'viewBox' => true,
        'viewbox' => true,
        'xmlns' => true,
        'width' => true,
        'height' => true,
        'fill' => true,
    ),
    'path' => array(
        'd' => true,
        'fill' => true,
    ),
    'circle' => array(
        'cx' => true,
        'cy' => true,
        'r' => true,
        'fill' => true,
    ),
);

$ui_svgs = array(
    'toggle' => '<svg viewBox="0 0 24 24"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.2L4 17.2V4h16v12z"/></svg>',
    'menu' => '<svg viewBox="0 0 24 24"><path d="M12 7a2 2 0 1 0-0.001-4.001A2 2 0 0 0 12 7zm0 2a2 2 0 1 0 0.001 4.001A2 2 0 0 0 12 9zm0 8a2 2 0 1 0 0.001 4.001A2 2 0 0 0 12 17z"/></svg>',
    'close' => '<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>',
    'send' => '<svg viewBox="0 0 24 24"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>',
    'footer' => '<svg viewBox="0 0 24 24"><path d="M7 2v11h3v9l7-12h-4l4-8z"/></svg>',
);

// Widget mode (popup) needs a toggle button
$is_widget = isset($mode) && $mode === 'widget';
$container_id = 'ai-platform-chatbot-' . esc_attr($chatbot->id);
$linked_forms_data = isset($linked_forms_data) && is_array($linked_forms_data) ? $linked_forms_data : array();
$linked_forms_attr = esc_attr(wp_json_encode($linked_forms_data));
?>

<?php
$container_classes = 'ai-platform-chatbot-container ';
$container_classes .= $is_widget ? 'ai-platform-chatbot-container--widget' : 'ai-platform-chatbot-container--inline';
if ($is_widget && $widget_position === 'bottom-left') {
    $container_classes .= ' ai-platform-chatbot-container--bottom-left';
}
?>
<div id="<?php echo esc_attr($container_id); ?>" 
     class="<?php echo esc_attr($container_classes); ?>"
     data-chatbot-id="<?php echo esc_attr($chatbot->id); ?>">

    <?php if ($is_widget): ?>
    <!-- Floating Toggle Button -->
    <button class="chatbot-widget-button" 
            type="button"
            style="--cb-primary-color: <?php echo esc_attr($primary_color); ?>"
            aria-label="<?php esc_attr_e('Open chat', 'kitsune-ai-platform'); ?>">
        <img class="chatbot-widget-button__avatar" src="<?php echo esc_url($avatar_url); ?>" alt="" />
        <span class="chatbot-widget-button__close"><?php echo wp_kses($ui_svgs['close'], $svg_allowed_tags); ?></span>
    </button>
    <?php endif; ?>

    <!-- Chatbot Widget -->
    <div class="<?php echo esc_attr(implode(' ', $widget_classes)); ?>"
         style="--cb-primary-color: <?php echo esc_attr($primary_color); ?>">
        
        <!-- Header -->
        <div class="chatbot-preview__header">
            <div class="chatbot-preview__avatar">
                <img src="<?php echo esc_url($avatar_url); ?>" alt="<?php esc_attr_e('Chatbot avatar', 'kitsune-ai-platform'); ?>" class="chatbot-preview__avatar-img" />
            </div>
            <div class="chatbot-preview__info">
                <div class="chatbot-preview__name"><?php echo esc_html($chatbot->name); ?></div>
                <div class="chatbot-preview__status">
                    <span class="chatbot-preview__status-dot"></span>
                    <?php esc_html_e('Online', 'kitsune-ai-platform'); ?>
                </div>
            </div>
            <div class="chatbot-preview__actions">
                <div class="chatbot-preview__menu">
                    <button class="chatbot-preview__menu-toggle" type="button" aria-label="<?php esc_attr_e('Menu', 'kitsune-ai-platform'); ?>" aria-expanded="false">
                        <?php echo wp_kses($ui_svgs['menu'], $svg_allowed_tags); ?>
                    </button>
                    <div class="chatbot-preview__menu-panel" role="menu" aria-label="<?php esc_attr_e('Chat options', 'kitsune-ai-platform'); ?>">
                        <button class="chatbot-preview__menu-item ai-platform-chatbot-end-session" type="button" role="menuitem">
                            <?php esc_html_e('End session', 'kitsune-ai-platform'); ?>
                        </button>
                    </div>
                </div>
                <?php if ($is_widget): ?>
                <button class="chatbot-preview__close ai-platform-chatbot-close" type="button" aria-label="<?php esc_attr_e('Close chat', 'kitsune-ai-platform'); ?>">
                    <?php echo wp_kses($ui_svgs['close'], $svg_allowed_tags); ?>
                </button>
                <?php endif; ?>
            </div>
        </div>

        <!-- Messages -->
        <div class="chatbot-preview__messages" id="<?php echo esc_attr($container_id); ?>-messages">
            <!-- Welcome Message -->
            <div class="chatbot-preview__message chatbot-preview__message--bot">
                <div class="chatbot-preview__bubble">
                    <?php echo esc_html($welcome_message); ?>
                </div>
            </div>
        </div>

        <!-- Suggested Questions -->
        <?php if (!empty($suggested_questions)): ?>
        <div class="chatbot-preview__suggestions" id="<?php echo esc_attr($container_id); ?>-suggestions"
             data-trigger="<?php echo esc_attr($suggestions_trigger); ?>"
             <?php if ($suggestions_trigger === 'first_interaction'): ?>style="display:none"<?php endif; ?>>
            <?php foreach ($suggested_questions as $question): ?>
                <?php if (!empty(trim($question))): ?>
                <button type="button" class="chatbot-preview__suggestion" data-question="<?php echo esc_attr($question); ?>">
                    <?php echo esc_html($question); ?>
                </button>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <div class="chatbot-preview__bottom">
            <!-- Input Area -->
            <div class="chatbot-preview__input-area">
                <div class="chatbot-preview__input-wrapper">
                    <input type="text" 
                           class="chatbot-preview__input ai-platform-chatbot-input" 
                           placeholder="<?php esc_attr_e('Write a message...', 'kitsune-ai-platform'); ?>"
                           id="<?php echo esc_attr($container_id); ?>-input" />
                    <button class="chatbot-preview__send-btn ai-platform-chatbot-send" type="button" aria-label="<?php esc_attr_e('Send message', 'kitsune-ai-platform'); ?>">
                        <?php echo wp_kses($ui_svgs['send'], $svg_allowed_tags); ?>
                    </button>
                </div>
            </div>

            <!-- Footer -->
            <?php
            $plugin_settings = get_option( 'kitsune_ai_platform_settings', array() );
            if ( ! empty( $plugin_settings['show_branding'] ) ) : ?>
            <div class="chatbot-preview__footer">
                <?php echo wp_kses($ui_svgs['footer'], $svg_allowed_tags); ?>
                <span><?php esc_html_e('Powered by AI', 'kitsune-ai-platform'); ?></span>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>
