/* global wp */
/**
 * Media Library Enhancements
 *
 * Adds bulk optimization button to media library
 *
 * @package
 */

import { __ } from '@wordpress/i18n';
import { useCallback, useState } from '@wordpress/element';
import { Button, Modal, Notice, Spinner, CheckboxControl, Card, CardBody } from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';

const BADGE_REQUEST_CONCURRENCY = 4;
const badgeQueue = [];
const badgePendingIds = new Set();
let badgeInFlight = 0;

/**
 * Bulk Image Optimizer Modal
 * @param root0
 * @param root0.isOpen
 * @param root0.onClose
 */
const BulkImageOptimizerModal = ({ isOpen, onClose }) => {
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [progress, setProgress] = useState({ current: 0, total: 0 });
  const [results, setResults] = useState([]);
  const [optimizeAll, setOptimizeAll] = useState(false);
  const [currentImage, setCurrentImage] = useState(null);
  const [errors, setErrors] = useState([]);
  const [runNotice, setRunNotice] = useState(null);

  const getSelectedAttachmentIds = useCallback(() => {
    if (wp.media && wp.media.frame) {
      const selected = wp.media.frame.state().get('selection');
      return selected.map((attachment) => attachment.id).filter((id) => id);
    }

    const selectedElements = document.querySelectorAll('.attachment.selected');
    return Array.from(selectedElements)
      .map((el) => {
        return el.getAttribute('data-id') || el.querySelector('input[type="checkbox"]')?.value;
      })
      .filter((id) => id);
  }, []);

  const selectedCount = optimizeAll ? 0 : getSelectedAttachmentIds().length;

  const startBulkOptimization = async () => {
    setIsOptimizing(true);
    setResults([]);
    setErrors([]);
    setCurrentImage(null);
    setRunNotice(null);

    try {
      // Get selected attachments or all images
      let attachmentIds = [];

      if (optimizeAll) {
        // Get all unoptimized images

        const response = await apiFetch({
          path: '/prorank-seo/v1/image-optimization/images/unoptimized',
          method: 'GET',
        });
        attachmentIds = response.attachment_ids || [];
      } else {
        attachmentIds = getSelectedAttachmentIds();
      }

      if (attachmentIds.length === 0) {
        setRunNotice({
          status: 'info',
          message: optimizeAll
            ? __('No unoptimized images were found for this batch.', 'prorank-seo')
            : __('Select one or more images in the media library before starting optimization.', 'prorank-seo'),
        });
        return;
      }

      setProgress({ current: 0, total: attachmentIds.length });

      // Process images one by one with enhanced tracking
      for (let i = 0; i < attachmentIds.length; i++) {
        const attachmentId = attachmentIds[i];
        setProgress({ current: i + 1, total: attachmentIds.length });
        
        // Get image info for progress display
        try {
          const imageInfo = await apiFetch({
            path: `/wp/v2/media/${attachmentId}`,
          });
          setCurrentImage({
            id: attachmentId,
            title: imageInfo.title?.rendered || `Image #${attachmentId}`,
            url: imageInfo.source_url,
          });
        } catch (e) {
          setCurrentImage({ id: attachmentId, title: `Image #${attachmentId}` });
        }

        try {
          const response = await apiFetch({
            path: '/prorank-seo/v1/image-optimization/images/optimize',
            method: 'POST',
            data: {
              attachment_id: attachmentId,
            },
          });

          setResults((prev) => [
            ...prev,
            {
              id: attachmentId,
              success: true,
              saved: response.saved_percent || 0,
              savedSize: response.saved_size || '0 KB',
              message: response.message,
              method: 'local',
              formats: {
                webp: response.webp_generated,
                avif: response.avif_generated,
              },
            },
          ]);
        } catch (error) {
          const errorMessage = error.message || __('Optimization failed', 'prorank-seo');
          
          setErrors((prev) => [
            ...prev,
            {
              id: attachmentId,
              message: errorMessage,
              timestamp: new Date().toISOString(),
            },
          ]);
          
          setResults((prev) => [
            ...prev,
            {
              id: attachmentId,
              success: false,
              message: errorMessage,
              retryable: !errorMessage.includes('Invalid') && !errorMessage.includes('not found'),
            },
          ]);
        }
      }

      setCurrentImage(null);
    } catch (error) {
      setRunNotice({
        status: 'error',
        message:
          error?.data?.message ||
          error?.message ||
          __('Unable to start bulk optimization for this batch.', 'prorank-seo'),
      });
    } finally {
      setIsOptimizing(false);
    }
  };

  const totalSaved =
    results.length > 0
      ? results.filter((r) => r.success).reduce((sum, r) => sum + (r.saved || 0), 0) / results.length
      : 0;

  return (
    <Modal
      title={__('Bulk Image Optimization', 'prorank-seo')}
      onRequestClose={onClose}
      className="prorank-bulk-optimizer-modal"
      isDismissible={true}
      style={{ maxWidth: '600px' }}
    >
      <div style={{ padding: '16px' }}>
        {!isOptimizing && results.length === 0 && (
          <>
            <p>
              {__(
                'Optimize multiple images at once to save storage space and improve loading times.',
                'prorank-seo'
              )}
            </p>

            <CheckboxControl
              label={__('Optimize all unoptimized images', 'prorank-seo')}
              checked={optimizeAll}
              onChange={setOptimizeAll}
            />

            {!optimizeAll && (
              <Notice status="info" isDismissible={false}>
                {__(
                  'Select images in the media library or check "Optimize all unoptimized images&quot; above.',
                  'prorank-seo'
                )}
              </Notice>
            )}

            {runNotice && (
              <Notice status={runNotice.status} isDismissible={false}>
                {runNotice.message}
              </Notice>
            )}

            <div style={{ marginTop: '20px' }}>
              <Button
                variant="primary"
                onClick={startBulkOptimization}
                disabled={!optimizeAll && selectedCount === 0}
              >
                {__('Start Optimization', 'prorank-seo')}
              </Button>
              <Button variant="secondary" onClick={onClose} style={{ marginLeft: '10px' }}>
                {__('Cancel', 'prorank-seo')}
              </Button>
            </div>
          </>
        )}

        {isOptimizing && (
          <div style={{ textAlign: 'center' }}>
            <Spinner />
            <p style={{ fontSize: '16px', fontWeight: 'bold' }}>
              {__('Optimizing images…', 'prorank-seo')}
            </p>
            
            {/* Current image info */}
            {currentImage && (
              <div style={{ marginBottom: '15px' }}>
                <p style={{ fontSize: '14px', color: '#666' }}>
                  {__('Processing:', 'prorank-seo')} {currentImage.title}
                </p>
                {currentImage.url && (
                  <img 
                    src={currentImage.url} 
                    alt={currentImage.title}
                    style={{ 
                      maxWidth: '150px', 
                      maxHeight: '150px', 
                      marginTop: '10px',
                      border: '1px solid #ddd',
                      borderRadius: '4px'
                    }}
                  />
                )}
              </div>
            )}
            
            {/* Progress indicator */}
            <p style={{ fontSize: '18px', marginBottom: '10px' }}>
              {progress.current} / {progress.total}
            </p>
            
            {/* Progress bar */}
            <div
              style={{
                width: '100%',
                height: '24px',
                background: '#f0f0f0',
                borderRadius: '12px',
                overflow: 'hidden',
                marginTop: '10px',
                position: 'relative',
              }}
            >
              <div
                style={{
                  width: `${(progress.current / progress.total) * 100}%`,
                  height: '100%',
                  background: '#0073aa',
                  transition: 'width 0.3s ease',
                }}
              />
              <span style={{
                position: 'absolute',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                color: '#fff',
                fontWeight: 'bold',
                fontSize: '12px',
              }}>
                {Math.round((progress.current / progress.total) * 100)}%
              </span>
            </div>

            {/* Error display */}
            {errors.length > 0 && (
              <div style={{ marginTop: '15px', maxHeight: '100px', overflow: 'auto' }}>
                <p style={{ color: '#dc3232', fontWeight: 'bold' }}>
                  {__('Errors encountered:', 'prorank-seo')}
                </p>
                {errors.slice(-3).map((error, idx) => (
                  <div key={idx} style={{ fontSize: '12px', color: '#666', marginTop: '5px' }}>
                    #{error.id}: {error.message}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {!isOptimizing && results.length > 0 && (
          <div>
            {/* Summary Statistics */}
            <div style={{ 
              display: 'grid', 
              gridTemplateColumns: '1fr 1fr 1fr', 
              gap: '15px',
              marginBottom: '20px'
            }}>
              <Card size="small">
                <CardBody style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#46b450' }}>
                    {results.filter(r => r.success).length}
                  </div>
                  <div style={{ fontSize: '12px', color: '#666' }}>
                    {__('Optimized', 'prorank-seo')}
                  </div>
                </CardBody>
              </Card>
              
              <Card size="small">
                <CardBody style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#0073aa' }}>
                    {(totalSaved || 0).toFixed(1)}%
                  </div>
                  <div style={{ fontSize: '12px', color: '#666' }}>
                    {__('Avg. Savings', 'prorank-seo')}
                  </div>
                </CardBody>
              </Card>
              
              <Card size="small">
                <CardBody style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', color: errors.length > 0 ? '#dc3232' : '#666' }}>
                    {errors.length}
                  </div>
                  <div style={{ fontSize: '12px', color: '#666' }}>
                    {__('Errors', 'prorank-seo')}
                  </div>
                </CardBody>
              </Card>
            </div>

            <Notice status="success" isDismissible={false}>
              {__('Optimization complete!', 'prorank-seo')}
            </Notice>

            {/* Detailed Results */}
            <div style={{ marginTop: '20px', maxHeight: '400px', overflow: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                  <tr style={{ borderBottom: '2px solid #ddd' }}>
                    <th style={{ padding: '8px', textAlign: 'left' }}>{__('Image', 'prorank-seo')}</th>
                    <th style={{ padding: '8px', textAlign: 'center' }}>{__('Status', 'prorank-seo')}</th>
                    <th style={{ padding: '8px', textAlign: 'center' }}>{__('Savings', 'prorank-seo')}</th>
                    <th style={{ padding: '8px', textAlign: 'center' }}>{__('Formats', 'prorank-seo')}</th>
                    <th style={{ padding: '8px', textAlign: 'center' }}>{__('Method', 'prorank-seo')}</th>
                  </tr>
                </thead>
                <tbody>
                  {results.map((result, index) => (
                    <tr
                      key={index}
                      style={{
                        borderBottom: '1px solid #eee',
                        backgroundColor: index % 2 === 0 ? '#f9f9f9' : '#fff',
                      }}
                    >
                      <td style={{ padding: '8px' }}>
                        #{result.id}
                      </td>
                      <td style={{ padding: '8px', textAlign: 'center' }}>
                        <span style={{ color: result.success ? '#46b450' : '#dc3232' }}>
                          {result.success ? '✓' : '✗'}
                        </span>
                      </td>
                      <td style={{ padding: '8px', textAlign: 'center' }}>
                        {result.success && result.saved > 0 ? (
                          <span>
                            <strong>{result.saved}%</strong>
                            {result.savedSize && (
                              <div style={{ fontSize: '11px', color: '#666' }}>
                                {result.savedSize}
                              </div>
                            )}
                          </span>
                        ) : (
                          '-'
                        )}
                      </td>
                      <td style={{ padding: '8px', textAlign: 'center' }}>
                        {result.formats ? (
                          <span style={{ fontSize: '11px' }}>
                            {result.formats.webp && <span style={{ color: '#46b450' }}>WebP </span>}
                            {result.formats.avif && <span style={{ color: '#0073aa' }}>AVIF</span>}
                          </span>
                        ) : '-'}
                      </td>
                      <td style={{ padding: '8px', textAlign: 'center', fontSize: '11px' }}>
                        {result.method || '-'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            
            {/* Retry failed optimizations */}
            {results.filter(r => !r.success && r.retryable).length > 0 && (
              <div style={{ marginTop: '15px' }}>
                <Button
                  variant="secondary"
                  onClick={() => {
                    const failedIds = results
                      .filter(r => !r.success && r.retryable)
                      .map(r => r.id);
                    // Reset and retry failed images
                    setResults([]);
                    setErrors([]);
                    startBulkOptimization();
                  }}
                >
                  {__('Retry Failed Images', 'prorank-seo')}
                </Button>
              </div>
            )}

            <div style={{ marginTop: '20px' }}>
              <Button variant="primary" onClick={onClose}>
                {__('Close', 'prorank-seo')}
              </Button>
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
};

/**
 * Initialize media library enhancements
 */
export const initializeMediaLibraryEnhancements = () => {
  // Only run on media library pages or when media modal is present
  const isMediaPage = window.location.href.includes('upload.php') ||
                      window.location.href.includes('media-new.php') ||
                      document.querySelector('.media-frame') ||
                      document.querySelector('#wp-media-grid');

  if (!isMediaPage) {
    // Not a media page, skip initialization silently
    return;
  }

  // Check if modules are enabled
  const aiImageAttributesEnabled = window.prorankSeo?.modules?.['ai-image-attributes'] || false;
  const imageOptimizationEnabled =
    window.prorankSeo?.modules?.['image-optimization'] ||
    window.prorankSeo?.modules?.image_optimization ||
    window.prorankSeo?.modules?.performance ||
    (window.prorankSeo?.modules?.developer_mode === true) ||
    false;

  if (!aiImageAttributesEnabled && !imageOptimizationEnabled) {
    return;
  }

  // Wait for media library toolbar to be available
  const toolbarSelectors = [
    '.media-toolbar-secondary',
    '.media-frame-toolbar .media-toolbar',
    '.attachments-browser .media-toolbar',
    '#wp-media-grid .media-toolbar',
  ];

  let attempts = 0;
  const maxAttempts = 20; // 10 seconds max

  const checkForToolbar = setInterval(() => {
    attempts++;
    let toolbar = null;

    for (const selector of toolbarSelectors) {
      toolbar = document.querySelector(selector);
      if (toolbar) break;
    }

    if (toolbar) {
      clearInterval(checkForToolbar);
      if (imageOptimizationEnabled) {
        addBulkOptimizerButton(toolbar);
      }
    } else if (attempts >= maxAttempts) {
      clearInterval(checkForToolbar);
    }
  }, 500);
};

/**
 * Add bulk optimizer button to media library toolbar
 * @param toolbar
 */
const addBulkOptimizerButton = (toolbar) => {
  // Check if button already exists
  if (toolbar.querySelector('.prorank-bulk-optimizer-button')) {
    return;
  }

  // Find existing ProRank AI button
  const existingAIButton = toolbar.querySelector('.prorank-bulk-ai-btn');

  // Check if we already have a ProRank button container
  let buttonContainer = toolbar.querySelector('.prorank-bulk-buttons-container');

  if (!buttonContainer) {
    // Create container for ProRank buttons
    buttonContainer = document.createElement('div');
    buttonContainer.className = 'prorank-bulk-buttons-container';
    buttonContainer.style.cssText = 'display: inline-flex; gap: 4px; margin-left: 6px;';

    // Find where to insert
    const bulkSelectButton = toolbar.querySelector(
      '.select-mode-toggle-button, button.media-button-select'
    );
    if (existingAIButton) {
      // Insert container where AI button is
      existingAIButton.parentNode.insertBefore(buttonContainer, existingAIButton);
      // Move AI button into container
      buttonContainer.appendChild(existingAIButton);
    } else if (bulkSelectButton) {
      bulkSelectButton.parentNode.insertBefore(buttonContainer, bulkSelectButton.nextSibling);
    } else {
      toolbar.appendChild(buttonContainer);
    }
  } else if (existingAIButton && !buttonContainer.contains(existingAIButton)) {
    // Move AI button into container if it's not already there
    buttonContainer.appendChild(existingAIButton);
  }

  // Create button to match AI alt text generator style
  const button = document.createElement('button');
  button.type = 'button';
  button.className = 'button button-secondary prorank-bulk-optimizer-button';

  const buttonIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  buttonIcon.setAttribute('viewBox', '0 0 24 24');
  buttonIcon.setAttribute('aria-hidden', 'true');
  buttonIcon.setAttribute('fill', 'none');
  buttonIcon.setAttribute('stroke', 'currentColor');
  buttonIcon.setAttribute('stroke-width', '1.5');
  buttonIcon.style.width = '20px';
  buttonIcon.style.height = '20px';
  buttonIcon.style.display = 'inline-block';
  buttonIcon.style.verticalAlign = 'middle';
  buttonIcon.style.marginRight = '4px';

  const buttonIconPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  buttonIconPath.setAttribute('stroke-linecap', 'round');
  buttonIconPath.setAttribute('stroke-linejoin', 'round');
  buttonIconPath.setAttribute(
    'd',
    'm2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z'
  );
  buttonIcon.appendChild(buttonIconPath);
  button.appendChild(buttonIcon);
  button.appendChild(document.createTextNode(__('Bulk Optimize Images', 'prorank-seo')));

  // Add button to container
  buttonContainer.appendChild(button);

  // Create React portal for modal only
  const modalRoot = document.createElement('div');
  document.body.appendChild(modalRoot);
  let modalReactRoot = null;

  // Handle button click
  button.addEventListener('click', (e) => {
    e.preventDefault();

    if (wp.element && wp.element.createElement && wp.element.render) {
      try {
        const { createElement } = wp.element;
        if (!modalReactRoot && wp.element.createRoot) {
          modalReactRoot = wp.element.createRoot(modalRoot);
        }
        const modalElement = createElement(BulkImageOptimizerModal, {
          isOpen: true,
          onClose: () => {
            if (modalReactRoot) {
              modalReactRoot.unmount();
              modalReactRoot = null;
            }
          },
        });
        modalReactRoot.render(modalElement);
      } catch (error) {}
    } else {
    }
  });
};

// Also add optimization badges to grid view images
const addOptimizationBadges = () => {
  const attachments = document.querySelectorAll('.attachment');

  attachments.forEach((attachment) => {
    if (
      attachment.classList.contains('prorank-badge-added') ||
      attachment.querySelector('.prorank-optimization-badge')
    ) {
      return;
    }

    const attachmentId = attachment.getAttribute('data-id');
    if (!attachmentId) return;

    if (!isImageGridAttachment(attachment)) {
      attachment.classList.add('prorank-badge-added');
      return;
    }

    queueBadgeRequest(attachment, attachmentId);
  });
};

const isImageGridAttachment = (attachment) => {
  return Boolean(attachment.querySelector('.attachment-preview.type-image'));
};

const queueBadgeRequest = (attachment, attachmentId) => {
  const id = String(attachmentId);

  if (badgePendingIds.has(id)) {
    return;
  }

  badgePendingIds.add(id);
  badgeQueue.push({ attachment, attachmentId: id });
  pumpBadgeQueue();
};

const pumpBadgeQueue = () => {
  while (badgeInFlight < BADGE_REQUEST_CONCURRENCY && badgeQueue.length > 0) {
    const job = badgeQueue.shift();
    badgeInFlight += 1;

    apiFetch({
      path: `/prorank-seo/v1/image-optimization/images/${job.attachmentId}/optimization-stats`,
    })
      .then((response) => {
        if (response?.optimized && response.stats) {
          const badge = document.createElement('div');
          badge.className = 'prorank-optimization-badge';

          const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
          svg.setAttribute('viewBox', '0 0 24 24');
          svg.setAttribute('aria-hidden', 'true');
          svg.style.width = '14px';
          svg.style.height = '14px';
          svg.style.display = 'inline-block';
          svg.style.verticalAlign = 'middle';
          svg.style.marginRight = '4px';
          svg.setAttribute('fill', 'currentColor');

          const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
          path.setAttribute('fill-rule', 'evenodd');
          path.setAttribute('clip-rule', 'evenodd');
          path.setAttribute('d', 'M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12Zm13.36-1.814a.75.75 0 1 0-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 0 0-1.06 1.06l2.25 2.25a.75.75 0 0 0 1.14-.094l3.75-5.25Z');
          svg.appendChild(path);

          const value = document.createElement('span');
          value.textContent = `${response.stats.saved_percent}%`;

          badge.appendChild(svg);
          badge.appendChild(value);
          badge.style.cssText = `
                    position: absolute;
                    bottom: 5px;
                    right: 5px;
                    background: rgba(0, 163, 42, 0.9);
                    color: white;
                    padding: 2px 6px;
                    border-radius: 3px;
                    font-size: 11px;
                    display: flex;
                    align-items: center;
                    gap: 2px;
                    z-index: 10;
                `;

          const thumbnail = job.attachment.querySelector('.thumbnail');
          if (thumbnail) {
            thumbnail.style.position = 'relative';
            thumbnail.appendChild(badge);
          }
        }
      })
      .catch(() => {
        // Ignore per-item failures. Badge decoration should never block media UI.
      })
      .finally(() => {
        job.attachment.classList.add('prorank-badge-added');
        badgePendingIds.delete(job.attachmentId);
        badgeInFlight -= 1;
        pumpBadgeQueue();
      });
  }
};

// Watch for media library grid updates
const gridObserver = new MutationObserver((mutations) => {
  for (const mutation of mutations) {
    if (mutation.addedNodes.length > 0) {
      // Debounce to avoid too many API calls
      clearTimeout(window.prorankBadgeTimeout);
      window.prorankBadgeTimeout = setTimeout(() => {
        addOptimizationBadges();
      }, 500);
    }
  }
});

// Start observing when media library is in grid mode
document.addEventListener('DOMContentLoaded', () => {
  const attachmentsBrowser = document.querySelector('.attachments-browser');
  if (attachmentsBrowser) {
    gridObserver.observe(attachmentsBrowser, {
      childList: true,
      subtree: true,
    });

    // Initial badge check
    setTimeout(() => addOptimizationBadges(), 1000);
  }

  // Add custom styles for ProRank bulk buttons
  const style = document.createElement('style');
  style.textContent = `
        /* Container for ProRank buttons */
        .prorank-bulk-buttons-container {
            display: inline-flex !important;
            align-items: center;
            gap: 4px;
            vertical-align: middle;
        }
        
        /* Ensure ProRank bulk buttons match and align */
        .prorank-bulk-ai-btn,
        .prorank-bulk-optimizer-button {
            display: inline-flex !important;
            align-items: center;
            gap: 6px;
            background: #f0f0f0 !important;
            border-color: #ccc !important;
            color: #2c3338 !important;
            margin: 0 !important;
            height: 32px !important;
            padding: 0 12px !important;
            font-size: 13px !important;
            line-height: 30px !important;
            vertical-align: middle !important;
            position: relative !important;
            top: 0 !important;
            box-sizing: border-box !important;
        }
        
        /* Fix AI button specific alignment issues - force override existing styles */
        .prorank-bulk-buttons-container .prorank-bulk-ai-btn {
            margin-top: 0 !important;
            margin-bottom: 0 !important;
            height: 32px !important;
            line-height: 30px !important;
            padding: 0 12px !important;
            vertical-align: middle !important;
            position: relative !important;
            top: 0 !important;
        }
        
        .prorank-bulk-ai-btn:hover,
        .prorank-bulk-optimizer-button:hover {
            background: #e5e5e5 !important;
            border-color: #999 !important;
            color: #2c3338 !important;
        }
        
        .prorank-bulk-ai-btn .dashicons,
        .prorank-bulk-optimizer-button .dashicons {
            width: 16px !important;
            height: 16px !important;
            font-size: 16px !important;
            line-height: 1 !important;
            margin: 0 !important;
            color: #2c3338 !important;
            vertical-align: middle !important;
            display: inline-block !important;
        }

        /* Fix icon color for AI button SVG */
        .prorank-bulk-ai-btn svg {
            color: #dba617 !important;
        }

        /* Hide old AI toolbar if it still appears */
        .prorank-bulk-ai-toolbar {
            display: none !important;
        }
        
        /* Ensure buttons stay together */
        .media-toolbar-secondary {
            display: flex !important;
            align-items: center !important;
            flex-wrap: wrap;
            gap: 6px;
        }
        
        /* Force all direct children of toolbar to align middle */
        .media-toolbar-secondary > * {
            vertical-align: middle !important;
        }
        
        /* Ensure our container doesn't break alignment */
        .media-toolbar-secondary .prorank-bulk-buttons-container {
            align-self: center !important;
        }
        
        .prorank-bulk-optimizer-modal .components-modal__header {
            border-bottom: 1px solid #ddd;
            margin-bottom: 0;
        }
        
        .prorank-optimization-badge {
            font-weight: 600;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        
        .prorank-optimization-badge .dashicons {
            font-size: 14px;
            width: 14px;
            height: 14px;
            line-height: 1;
        }
    `;
  document.head.appendChild(style);
});
