/* global wp */
/**
 * Media Modal Enhancements
 *
 * Adds AI Alt Text and Image Optimizer buttons to media modal
 *
 * @package
 */

import { __ } from '@wordpress/i18n';
import { useState, useEffect } from '@wordpress/element';
import { Button, Notice, Spinner } from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';

const $ = window.jQuery;

// AI Alt Text Button Component removed - handled by ai-image-attributes.js module

/**
 * Image Optimizer Button Component
 * @param root0
 * @param root0.attachment
 */
const ImageOptimizerButton = ({ attachment }) => {
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [message, setMessage] = useState(null);
  const [isOptimized, setIsOptimized] = useState(false);
  const [stats, setStats] = useState(null);

  // Check if module is enabled - try multiple possible keys
  const modules = window.prorankSeo?.modules || {};
  const imageOptimizationEnabled =
    modules['image-optimization'] ||
    modules.image_optimization ||
    modules.performance ||
    modules.images ||
    false;

  if (!imageOptimizationEnabled) {
    return null;
  }

  // Check optimization status on mount
  useEffect(() => {
    const checkStatus = async () => {
      try {
        const response = await apiFetch({
          path: `/prorank-seo/v1/image-optimization/images/${attachment.id}/optimization-stats`,
        });

        if (response.optimized && response.stats) {
          setIsOptimized(true);
          setStats(response.stats);
        }
      } catch (error) {
        // Ignore errors for status check
      }
    };

    if (attachment.id) {
      checkStatus();
    }
  }, [attachment.id]);

  const optimizeImage = async () => {
    setIsOptimizing(true);
    setMessage(null);

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

      if (response.success) {
        setMessage({
          type: 'success',
          text: __('Image optimized! Saved ', 'prorank-seo') + (response.saved_size || '0 KB'),
        });

        // Update optimization status
        setIsOptimized(true);
        setStats({
          original_size: response.original_size,
          optimized_size: response.new_size,
          saved_size: response.saved_size,
          saved_percent: response.saved_percent,
          optimization_date: new Date().toISOString(),
        });

        // Refresh attachment data
        attachment.fetch();
      } else {
        throw new Error(response.message || __('Failed to optimize image', 'prorank-seo'));
      }
    } catch (error) {
      setMessage({
        type: 'error',
        text: error.message || __('Failed to optimize image', 'prorank-seo'),
      });
    } finally {
      setIsOptimizing(false);
    }
  };

  return (
    <div
      className="prorank-image-optimizer"
      style={{
        marginTop: '8px',
        display: 'block',
        clear: 'both',
        width: '100%',
        textAlign: 'right',
      }}
    >
      {message && (
        <Notice
          status={message.type}
          isDismissible={true}
          onRemove={() => setMessage(null)}
          style={{ marginBottom: '8px', textAlign: 'left' }}
        >
          {message.text}
        </Notice>
      )}

      {isOptimized && stats && (
        <div
          style={{
            background: '#f0f8ff',
            border: '1px solid #d3e3f0',
            borderRadius: '4px',
            padding: '8px',
            marginBottom: '8px',
            fontSize: '12px',
            textAlign: 'left',
          }}
        >
          <strong>{__('Optimized:', 'prorank-seo')}</strong> {__('Saved', 'prorank-seo')}{' '}
          {stats.saved_percent}%
        </div>
      )}

      <Button
        variant="secondary"
        onClick={optimizeImage}
        isBusy={isOptimizing}
        disabled={isOptimizing}
        className="prorank-optimize-btn"
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          justifyContent: 'center',
          gap: '6px',
          padding: '6px 12px',
          fontSize: '13px',
          width: 'auto',
          marginLeft: 'auto',
        }}
      >
        {isOptimizing ? (
          <>
            <Spinner style={{ margin: '0 4px 0 0' }} />
            {__('Optimizing…', 'prorank-seo')}
          </>
        ) : isOptimized ? (
          __('Re-optimize Image', 'prorank-seo')
        ) : (
          __('Optimize Image', 'prorank-seo')
        )}
      </Button>
    </div>
  );
};

/**
 * Initialize media enhancements
 */
export const initializeMediaEnhancements = () => {
  // Check if we're in a context where wp.media should exist
  if (typeof wp === 'undefined' || !wp || !wp.media) {
    // Only try to initialize on pages that actually use the media library
    const isMediaPage =
      document.body.classList.contains('upload-php') ||
      document.body.classList.contains('post-php') ||
      document.body.classList.contains('post-new-php') ||
      document.querySelector('.media-modal') ||
      document.querySelector('#set-post-thumbnail');

    if (isMediaPage) {
      // Try again after DOM is ready
      if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
          setTimeout(() => {
            if (window.wp && window.wp.media) {
              initializeMediaEnhancements();
            }
          }, 1000);
        });
      }
    }

    return;
  }

  // Override attachment details views for both regular and featured image modals
  const viewsToExtend = [];

  if (wp.media.view.Attachment && wp.media.view.Attachment.Details) {
    // For featured image modal
    if (wp.media.view.Attachment.Details) {
      viewsToExtend.push({
        path: 'Details',
        view: wp.media.view.Attachment.Details,
      });
    }

    // For media library modal
    if (wp.media.view.Attachment.Details.TwoColumn) {
      viewsToExtend.push({
        path: 'Details.TwoColumn',
        view: wp.media.view.Attachment.Details.TwoColumn,
      });
    }
  }

  viewsToExtend.forEach(({ path, view }) => {
    const OriginalView = view;
    const pathParts = path.split('.');

    if (pathParts.length === 1) {
      wp.media.view.Attachment.Details = OriginalView.extend({
        initialize() {
          OriginalView.prototype.initialize.apply(this, arguments);
          this.on('ready', this.addEnhancements, this);
        },

        addEnhancements() {
          const attachment = this.model;

          if (!attachment || attachment.get('type') !== 'image') {
            return;
          }

          // Use a slight delay to ensure DOM is ready
          setTimeout(() => {
            injectButtonsForAttachment(attachment, this.$el);
          }, 50);
        },
      });
    } else {
      wp.media.view.Attachment.Details.TwoColumn = OriginalView.extend({
        initialize() {
          OriginalView.prototype.initialize.apply(this, arguments);
          this.on('ready', this.addEnhancements, this);
        },

        addEnhancements() {
          const attachment = this.model;

          if (!attachment || attachment.get('type') !== 'image') {
            return;
          }

          // Use a slight delay to ensure DOM is ready
          setTimeout(() => {
            injectButtonsForAttachment(attachment, this.$el);
          }, 50);
        },
      });
    }
  });

  // Also handle media frame events
  wp.media.frame = wp.media.frame || null;

  // Handle attachment details when they're inserted into DOM
  $(document).on('DOMNodeInserted', '.attachment-details', function () {
    setTimeout(() => {
      if (wp.media.frame) {
        const selection = wp.media.frame.state().get('selection');
        if (selection && selection.length) {
          const attachment = selection.first();
          if (attachment && attachment.get('type') === 'image') {
            injectButtonsForAttachment(attachment, $(this));
          }
        }
      }
    }, 100);
  });

  // Special handling for featured image modal
  const originalFeaturedImageFrame = wp.media.featuredImage && wp.media.featuredImage.frame;
  if (originalFeaturedImageFrame) {
    wp.media.featuredImage.frame = function () {
      const frame = originalFeaturedImageFrame.apply(this, arguments);

      // Listen for when an image is selected
      frame.on('selection:toggle', function () {
        setTimeout(() => {
          const selection = frame.state().get('selection');
          if (selection && selection.length) {
            const attachment = selection.first();
            if (attachment && attachment.get('type') === 'image') {
              const container = frame.$el.find('.attachment-details');
              if (container.length) {
                injectButtonsForAttachment(attachment, container);
              }
            }
          }
        }, 100);
      });

      return frame;
    };
  }
};

/**
 * Inject buttons for a specific attachment
 * @param attachment
 * @param container
 */
const injectButtonsForAttachment = (attachment, container) => {
  // Ensure we have jQuery container
  const $container = container.jquery ? container : $(container);

  // Skip AI button - it's handled by ai-image-attributes.js module
  // Only add the image optimizer button

  // Find location for optimizer button
  const settingsContainer = $container.find('.settings')[0];
  if (settingsContainer && !document.querySelector('#prorank-optimizer-button-' + attachment.id)) {
    // Create wrapper div for optimizer button
    const optimizerWrapper = document.createElement('div');
    optimizerWrapper.className = 'setting prorank-optimizer-setting';
    optimizerWrapper.style.cssText = 'margin-top: 8px;';

    // Create container for optimizer button
    const optimizerContainer = document.createElement('div');
    optimizerContainer.id = 'prorank-optimizer-button-' + attachment.id;
    optimizerWrapper.appendChild(optimizerContainer);

    // Append to settings
    settingsContainer.appendChild(optimizerWrapper);

    // Render optimizer button
    if (wp.element && wp.element.createRoot) {
      const { createElement, createRoot } = wp.element;
      const element = createElement(ImageOptimizerButton, { attachment });
      const root = createRoot(optimizerContainer);
      root.render(element);
    }
  }
};

/**
 * Inject buttons into the media modal (legacy)
 */
const injectButtons = () => {
  // Get the current attachment
  const frame = wp.media.frame;
  if (!frame) {
    return;
  }

  const selection = frame.state().get('selection');
  if (!selection || !selection.length) {
    return;
  }

  const attachment = selection.first();
  if (!attachment || attachment.get('type') !== 'image') {
    return;
  }

  // AI Alt Text button is now handled by ai-image-attributes.js module
  // See includes/Modules/AI/AIImageAttributes.php

  // Find settings container or create a new section for optimize button
  const settingsContainer = document.querySelector('.attachment-details .settings');
  const attachmentInfo = document.querySelector('.attachment-details .attachment-info');
  const compat = document.querySelector('.attachment-details .compat-meta');

  // Try multiple locations to inject the optimizer button
  let targetContainer = null;

  // Option 1: After the last setting
  if (settingsContainer) {
    const lastSetting = settingsContainer.querySelector('.setting:last-child');
    if (lastSetting && !document.querySelector('#prorank-optimizer-button-' + attachment.id)) {
      targetContainer = lastSetting;
    }
  }

  // Option 2: In attachment info section
  if (
    !targetContainer &&
    attachmentInfo &&
    !attachmentInfo.querySelector('.prorank-image-optimizer')
  ) {
    targetContainer = attachmentInfo;
  }

  // Option 3: After compat meta
  if (!targetContainer && compat && !compat.querySelector('.prorank-image-optimizer')) {
    targetContainer = compat.parentElement;
  }

  if (targetContainer && !document.querySelector('#prorank-optimizer-button-' + attachment.id)) {
    // Create wrapper div for optimizer button
    const optimizerWrapper = document.createElement('div');
    optimizerWrapper.className = 'setting prorank-optimizer-setting';
    optimizerWrapper.style.cssText = 'margin-top: 8px;';

    // Create container for optimizer button
    const optimizerContainer = document.createElement('div');
    optimizerContainer.id = 'prorank-optimizer-button-' + attachment.id;
    optimizerWrapper.appendChild(optimizerContainer);

    // Insert after target container
    if (targetContainer === attachmentInfo) {
      targetContainer.appendChild(optimizerWrapper);
    } else {
      targetContainer.parentNode.insertBefore(optimizerWrapper, targetContainer.nextSibling);
    }

    // Render optimizer button
    if (wp.element && wp.element.createRoot) {
      const root = wp.element.createRoot(optimizerContainer);
      root.render(<ImageOptimizerButton attachment={attachment} />);
    }
  }
};

// Re-inject buttons when media modal content updates
const observer = new MutationObserver((mutations) => {
  for (const mutation of mutations) {
    if (mutation.type === 'childList' && mutation.target.classList.contains('media-modal')) {
      setTimeout(() => {
        injectButtons();
      }, 100);
      break;
    }
  }
});

// Start observing when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
  const mediaModal = document.querySelector('.media-modal');
  if (mediaModal) {
    observer.observe(mediaModal, { childList: true, subtree: true });
  }
});
