<?php
if (!defined('ABSPATH')) exit;

add_action('wp_enqueue_scripts', function () {
  if (is_admin() || is_feed() || is_preview()) return;

  // Ensure the function exists before calling it
  if (!function_exists('webability_acwg_get_options')) {
    return;
  }

  $o = webability_acwg_get_options();
  if (empty($o['enabled'])) return;
  if (!empty($o['exclude_logged']) && is_user_logged_in()) return;
  if (function_exists('is_amp_endpoint') && is_amp_endpoint()) return;

  // Enqueue WebAbility script with user settings
  wp_enqueue_script(
    'webability-widget',
    'https://widget-v2.webability.io/widget.min.js',
    array(),
    '1.0.0',
    true // Load in footer
  );
  
  // Add script attributes via wp_script_add_data
  wp_script_add_data('webability-widget', 'defer', true);
  
  // Add custom attributes via filter
  add_filter('script_loader_tag', function($tag, $handle) use ($o) {
    if ($handle === 'webability-widget') {
      $position = esc_attr($o['position']);
      $offset = esc_attr($o['offset_x'] . ',' . $o['offset_y']);
      $lang = esc_attr(isset($o['language']) ? $o['language'] : 'en');
      $color = esc_attr(isset($o['widget_color']) ? $o['widget_color'] : '#2563eb');
      $size_raw = isset($o['trigger_size']) ? $o['trigger_size'] : 'medium';
      $size = esc_attr($size_raw);
      $icon_type_raw = isset($o['icon_type']) ? $o['icon_type'] : 'm-full';

      // The widget reads launcher size from the size prefix on data-asw-icon-type
      // (s-full, m-full, l-full, etc.) — not from data-asw-size. Sync the user's
      // Trigger Size selection into the icon-type prefix so the dropdown actually
      // resizes the launcher. Was a no-op before this commit.
      $size_prefix_map = ['small' => 's', 'medium' => 'm', 'large' => 'l'];
      $size_prefix = isset($size_prefix_map[$size_raw]) ? $size_prefix_map[$size_raw] : 'm';
      // Replace the leading prefix on icon-type if it already has one (s-/m-/l-);
      // otherwise prepend the size prefix.
      if (preg_match('/^[sml]-/', $icon_type_raw)) {
        $icon_type_synced = $size_prefix . substr($icon_type_raw, 1);
      } else {
        $icon_type_synced = $size_prefix . '-' . $icon_type_raw;
      }
      $icon_type = esc_attr($icon_type_synced);

      $attrs = ' data-asw-lang="' . $lang . '"'
             . ' data-asw-position="' . $position . '"'
             . ' data-asw-debug="false"'
             . ' data-asw-analyzer="true"'
             . ' data-asw-offset="' . $offset . '"'
             . ' data-asw-color="' . $color . '"'
             . ' data-asw-size="' . $size . '"'
             . ' data-asw-icon-type="' . $icon_type . '"'
             . ' data-no-optimize="1"'
             . ' defer';

      $tag = str_replace(' src=', $attrs . ' src=', $tag);
    }
    return $tag;
  }, 10, 2);
}, 20);
