<?php

declare(strict_types=1);

namespace KimaAI\ChatBot;

use KimaAI\Admin\Settings;
use KimaAI\Admin\SettingsI18n;

defined('ABSPATH') || exit;

class ChatbotAssets {

  /**
   * Create the chatbot assets handler.
   *
   * @param Settings $settings Plugin settings.
   */
  public function __construct(private Settings $settings) {
  }

  /**
   * Register WordPress action and shortcode hooks.
   *
   * @return void
   */
  public function registerHooks(): void {
    add_shortcode('kimaai_chatbot', [$this, 'chatBotShortCode']);

    // PHP_INT_MAX ensures this runs after all other scripts/styles are enqueued.
    add_action('wp_enqueue_scripts', [$this, 'maybeEnqueueAssets'], PHP_INT_MAX);

    // Add chatbot assets in the admin area
    add_action('admin_enqueue_scripts', [$this, 'enqueueAssets'], PHP_INT_MAX);
  }

  /**
   * Enqueues the chatbot assets if the shortcode is present.
   */
  public function maybeEnqueueAssets(): void {
    if ($this->isEnableGlobally() || $this->isShortcodePresent()) {
      $this->enqueueAssets();
    }

    // If enabled globally, also place the chatbot in the footer.
    if ($this->isEnableGlobally()) {
      add_action('wp_footer', [$this, 'placeChatBot']);
    }
  }

  /**
   * Checks if the current post content contains the chatbot shortcode.
   *
   * @return bool True if shortcode is present, false otherwise.
   */
  protected function isShortcodePresent(): bool {
    if (is_singular()) {
      global $post;
      if (!empty($post->post_content) && has_shortcode($post->post_content, 'kimaai_chatbot')) {
        return true;
      }
    }
    return false;
  }

  /**
   * Chatbot shortcode
   *
   * @return string
   */
  public function chatBotShortCode(): string {
    ob_start();
    $this->placeChatBot();
    return ob_get_clean();
  }


  /**
   * Generate dynamic CSS
   *
   * @return string
   */
  public function generateDynamicCss(): string {
    $appearance = $this->settings->getOption(null, 'chatbot', 'appearance');

    if (!is_array($appearance)) {
      $appearance = [];
    }

    $theme = ChatbotTheme::normalize($appearance);
    $vars = ChatbotTheme::cssVars($theme);

    /**
     * Filter token-based chatbot CSS variables.
     *
     * @param array $vars Final CSS variables.
     * @param array $theme Normalized theme configuration.
     * @param array $appearance Raw appearance settings.
     */
    $vars = apply_filters('kimaai_chatbot_theme_vars', $vars, $theme, $appearance);

    $legacy_theme = [
      'bodyBgColor' => $theme['advanced']['bodyBackground'] ?? $theme['colors']['primary'],
      'bodyTextColor' => $theme['advanced']['bodyText'] ?? '#ffffff',
      'userMessageBgColor' => $theme['advanced']['userMessageBackground'] ?? $theme['colors']['primary'],
      'userMessageTextColor' => $theme['advanced']['userMessageText'] ?? '#ffffff',
      'aiMessageBgColor' => $theme['advanced']['aiMessageBackground'] ?? 'color-mix(in oklch, var(--kimaai-chatbot-primary) 7%, var(--kimaai-white))',
      'aiMessageTextColor' => $theme['advanced']['aiMessageText'] ?? $theme['colors']['neutral'],
    ];
    $filtered_legacy_theme = apply_filters('kimaai_chatbot_theme', $legacy_theme);

    if ($filtered_legacy_theme !== $legacy_theme) {
      $vars['--kimaai-chatbot-primary'] = $filtered_legacy_theme['bodyBgColor'];
      $vars['--kimaai-chatbot-text-override'] = $filtered_legacy_theme['bodyTextColor'];
      $vars['--kimaai-chatbot-body-override'] = $filtered_legacy_theme['bodyBgColor'];
      $vars['--kimaai-chatbot-header-background-override'] = $filtered_legacy_theme['bodyBgColor'];
      $vars['--kimaai-chatbot-header-text-override'] = $filtered_legacy_theme['bodyTextColor'];
      $vars['--kimaai-chatbot-user-message-background-override'] = $filtered_legacy_theme['userMessageBgColor'];
      $vars['--kimaai-chatbot-user-message-text-override'] = $filtered_legacy_theme['userMessageTextColor'];
      $vars['--kimaai-chatbot-ai-message-background-override'] = $filtered_legacy_theme['aiMessageBgColor'];
      $vars['--kimaai-chatbot-ai-message-text-override'] = $filtered_legacy_theme['aiMessageTextColor'];
    }

    $css = "#kimaai-chatbot.kimaai-chatbot {\n";
    foreach ($vars as $name => $value) {
      if (!is_string($value) || trim($value) === '') {
        continue;
      }

      $css .= sprintf("  %s: %s;\n", $name, $value);
    }
    $css .= "}\n";

    return function_exists('wp_kses_post') ? wp_kses_post($css) : $css;
  }

  /**
   * Place the chatbot
   */
  public function placeChatBot(): void {
    $chatbot_settings = $this->settings->getOption(null, 'chatbot');
    $appearance = is_array($chatbot_settings['appearance'] ?? null) ? $chatbot_settings['appearance'] : [];
    $theme = ChatbotTheme::normalize($appearance);
    $attrs = ChatbotTheme::rootAttributes($theme);

    printf(
      '<div id="kimaai-chatbot" class="kimaai-chatbot" data-kimaai-mode="%s" data-kimaai-style="%s" data-kimaai-color-preset="%s"></div>',
      $this->escapeAttribute($attrs['data-kimaai-mode']),
      $this->escapeAttribute($attrs['data-kimaai-style']),
      $this->escapeAttribute($attrs['data-kimaai-color-preset'])
    );
  }

  /**
   * Enqueues the chatbot assets.
   */
  public function enqueueAssets(): void {
    $asset_info = include_once KIMAAI_PLUGIN_PATH . 'build/chatbot/index.asset.php';

    wp_register_style(
      'kimaai-chatbot',
      KIMAAI_PLUGIN_URL . 'build/chatbot.css',
      [],
      $asset_info['version']
    );
    wp_enqueue_style('kimaai-chatbot');

    wp_register_script(
      'kimaai-chatbot',
      KIMAAI_PLUGIN_CHATBOT_ASSETS . 'index.js',
      $asset_info['dependencies'],
      $asset_info['version'],
      true
    );

    wp_set_script_translations(
      'kimaai-chatbot',
      'kimaai',
      KIMAAI_PLUGIN_PATH . 'languages'
    );
    wp_enqueue_script('kimaai-chatbot');

    $chatbot_settings = $this->settings->getOption(null, 'chatbot');
    $appearance_settings = $chatbot_settings['appearance'];
    $settings = $chatbot_settings['settings'];
    $is_user_logged_in = is_user_logged_in();

    wp_localize_script(
      'kimaai-chatbot',
      'kimaaiChatbot',
      [
        'restRoot' => esc_url_raw(rest_url()),
        'chatbotApi' => esc_url_raw(rest_url('kimaai/v1/chatbot')),
        'chatbotHistoryApi' => esc_url_raw(rest_url('kimaai/v1/chatbot/history')),
        'chatbotHistoryClearApi' => esc_url_raw(rest_url('kimaai/v1/chatbot/history/clear')),
        'chatbotFeedbackMessageApi' => esc_url_raw(rest_url('kimaai/v1/chatbot/feedback/message')),
        'chatbotFeedbackCsatApi' => esc_url_raw(rest_url('kimaai/v1/chatbot/feedback/csat')),
        'postId' => get_the_ID(),
        'isLoggedIn' => $is_user_logged_in,
        'nonce' => $is_user_logged_in ? wp_create_nonce('wp_rest') : '',
        'i18n' => [
          'lang' => SettingsI18n::getCurrentLang(),
          'defaultLang' => SettingsI18n::getDefaultLang(),
          'i18nActive' => SettingsI18n::isIntegrationActive(),
          'provider' => SettingsI18n::isWpmlActive() ? 'wpml' : (SettingsI18n::isPolylangActive() ? 'polylang' : null),
        ],
        'settings' => [
          'isEnable' => $appearance_settings['isEnable'],
          'position' => $appearance_settings['position'],
          'icon' => $appearance_settings['icon'],
          'customIconUrl' => $appearance_settings['customIconUrl'],
          'showHeaderIcon' => $appearance_settings['showHeaderIcon'],
          'aiAvatarIcon' => $appearance_settings['aiAvatarIcon'],
          'aiAvatarUrl' => $appearance_settings['aiAvatarUrl'],
          'userAvatarIcon' => $appearance_settings['userAvatarIcon'],
          'userAvatarUrl' => $appearance_settings['userAvatarUrl'],
          'offsetBottom' => $appearance_settings['offset']['bottom'],
          'offsetSide' => $appearance_settings['offset']['right'],
          'showMessageCopyButton' => $appearance_settings['showMessageCopyButton'],
          'chatTitle' => $appearance_settings['chatTitle'],
          'chatName' => $appearance_settings['chatName'],
          'placeholder' => $appearance_settings['placeholder'],
          'greeting' => $appearance_settings['greeting'],
          'disclaimer' => $appearance_settings['disclaimer'],
          'poweredBy' => $appearance_settings['poweredBy'],
          'attentionEnabled' => $appearance_settings['attentionEnabled'],
          'attentionShowQuickActions' => $appearance_settings['attentionShowQuickActions'],
          'attentionMessage' => $appearance_settings['attentionMessage'],
          'attentionDelay' => $appearance_settings['attentionDelay'] * 1000,
          'attentionSound' => $appearance_settings['attentionSound'],
          'attentionShowOnceWhenClickOnClose' => $appearance_settings['attentionShowOnceWhenClickOnClose'],
          'attentionShowOnceWhenInteracted' => $appearance_settings['attentionShowOnceWhenInteracted'],
          'messageFeedback' => $settings['messageFeedback'],
          'csatFeedback' => $settings['csatFeedback'],
          'gdprConsent' => $settings['gdprConsent'],
          'gdprText' => $settings['gdprText'],
          'streaming' => $settings['streaming'],
        ],
      ]
    );

    wp_add_inline_style('kimaai-chatbot', $this->generateDynamicCss());
  }

  /**
   * Returns whether the chatbot is enabled or disabled globally.
   *
   * @return bool True if the chatbot is enabled, false otherwise.
   */
  public function isEnableGlobally(): bool {
    return apply_filters('kimaai_chatbot_should_load', (bool) $this->settings->getOption('isEnable', 'chatbot'));
  }

  /**
   * Escapes HTML attribute values in runtime and tests.
   *
   * @param string $value Raw attribute value.
   * @return string
   */
  private function escapeAttribute(string $value): string {
    if (function_exists('esc_attr')) {
      return esc_attr($value);
    }

    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  }
}
