// Content script for XiaoYuZhou podcast pages
// Adds subscribe button and episode action buttons

(function() {
  'use strict';

  const PODCAST_PATH_REGEX = /^\/podcast\/([a-f0-9]+)/;

  // Extract podcast ID from current URL
  function getPodcastIdFromUrl() {
    const match = window.location.pathname.match(PODCAST_PATH_REGEX);
    return match ? match[1] : null;
  }

  // Extract podcast data from __NEXT_DATA__
  function extractPodcastData() {
    const scriptTag = document.getElementById('__NEXT_DATA__');
    if (!scriptTag) {
      console.warn('[核桃FM] __NEXT_DATA__ not found');
      return null;
    }

    try {
      const nextData = JSON.parse(scriptTag.textContent);
      const podcast = nextData?.props?.pageProps?.podcast;

      if (!podcast) {
        console.warn('[核桃FM] Podcast data not found in __NEXT_DATA__');
        return null;
      }

      return {
        id: podcast.pid || podcast.id,
        title: podcast.title || '',
        author: podcast.author || '',
        description: podcast.description || '',
        image: podcast.image?.picUrl || '',
        source: 'xiaoyuzhou',
        sourceRef: podcast.pid || podcast.id,
      };
    } catch (err) {
      console.error('[核桃FM] Failed to parse podcast data:', err);
      return null;
    }
  }

  // Extract episode ID from card element
  function extractEpisodeIdFromCard(cardElement) {
    try {
      // The card itself might be the link, or find link inside
      let linkElement = cardElement;
      if (!cardElement.href) {
        linkElement = cardElement.querySelector('a[href*="/episode/"]');
      }

      if (!linkElement || !linkElement.href) return null;

      const episodeIdMatch = linkElement.href.match(/\/episode\/([a-f0-9]+)/);
      if (!episodeIdMatch) return null;

      return episodeIdMatch[1];
    } catch (err) {
      console.error('[核桃FM] Failed to extract episode ID from card:', err);
      return null;
    }
  }

  // Fetch full episode data from background
  async function fetchEpisodeData(episodeId) {
    try {
      console.log('[核桃FM] Fetching episode data for:', episodeId);

      const response = await chrome.runtime.sendMessage({
        type: 'fetchEpisode',
        episodeId: episodeId,
      });

      console.log('[核桃FM] Fetch response:', response);

      if (response && response.ok !== false) {
        let episode = null;

        // Response format: { ok: true, episode: {...}, meta: {...} }
        if (response.episode) {
          episode = response.episode;
        }
        // Sometimes the episode data is spread directly in the response
        else if (response.id && response.audioUrl) {
          episode = response;
        }

        // Use podcast image instead of episode image
        if (episode) {
          const podcastData = extractPodcastData();
          if (podcastData && podcastData.image) {
            episode.image = podcastData.image;
            episode.cover = podcastData.image;
          }
          return episode;
        }
      }

      throw new Error(response?.error || 'Failed to fetch episode data');
    } catch (err) {
      console.error('[核桃FM] Failed to fetch episode data:', err);
      throw err;
    }
  }

  // Check if podcast is already subscribed
  async function isPodcastSubscribed(podcastId) {
    try {
      const response = await chrome.runtime.sendMessage({
        type: 'xyz.checkSubscription',
        podcastId: podcastId,
      });
      return response && response.subscribed === true;
    } catch (err) {
      console.error('[核桃FM] Failed to check subscription:', err);
      return false;
    }
  }

  // Check if podcast is already subscribed
  async function isPodcastSubscribed(podcastId, podcastTitle) {
    try {
      const response = await chrome.runtime.sendMessage({
        type: 'xyz.checkSubscription',
        podcastId: podcastId,
        podcastTitle: podcastTitle,
      });
      return response && response.subscribed === true;
    } catch (err) {
      console.error('[核桃FM] Failed to check subscription:', err);
      return false;
    }
  }

  // Add subscribe button after podcast title
  async function injectSubscribeButton() {
    const podcastId = getPodcastIdFromUrl();
    if (!podcastId) return;

    // Check if button already exists
    if (document.getElementById('xyz-fm-subscribe-btn')) {
      return;
    }

    const podcastData = extractPodcastData();
    if (!podcastData) return;

    // Check if already subscribed
    const isSubscribed = await isPodcastSubscribed(podcastId, podcastData.title);

    // Find title element (sibling of avatar-wrapper)
    const titleElement = document.querySelector('.avatar-wrapper + .title');
    if (!titleElement) {
      console.warn('[核桃FM] Could not find title element');
      return;
    }

    // Create subscribe container
    const subscribeContainer = document.createElement('span');
    subscribeContainer.id = 'xyz-fm-subscribe-container';
    subscribeContainer.style.cssText = `
      display: inline-flex;
      align-items: center;
      gap: 6px;
      margin-left: 12px;
      padding: 4px 8px 4px 6px;
      background: linear-gradient(135deg, #f0fdf4 0%, #ecfdf5 100%);
      border-radius: 16px;
      border: 1px solid #d1fae5;
      vertical-align: middle;
    `;

    const logo = document.createElement('img');
    logo.src = chrome.runtime.getURL('images/logo.png');
    logo.alt = '核桃FM';
    logo.style.cssText = `
      width: 16px;
      height: 16px;
      border-radius: 3px;
    `;
    subscribeContainer.appendChild(logo);

    const subscribeButton = document.createElement('button');
    subscribeButton.id = 'xyz-fm-subscribe-btn';
    subscribeButton.textContent = isSubscribed ? '已订阅' : '订阅';
    subscribeButton.disabled = isSubscribed;
    subscribeButton.style.cssText = `
      padding: 4px 12px;
      background: ${isSubscribed ? '#6366f1' : '#10b981'};
      color: white;
      border: none;
      border-radius: 12px;
      font-size: 13px;
      font-weight: 500;
      cursor: ${isSubscribed ? 'not-allowed' : 'pointer'};
      opacity: ${isSubscribed ? '0.7' : '1'};
      transition: all 0.2s;
    `;

    if (!isSubscribed) {
      subscribeButton.addEventListener('click', async () => {
        subscribeButton.disabled = true;
        subscribeButton.textContent = '订阅中...';

        try {
          const response = await chrome.runtime.sendMessage({
            type: 'xyz.subscribe',
            podcast: podcastData,
          });

          if (response && response.ok !== false) {
            subscribeButton.textContent = '已订阅';
            subscribeButton.style.background = '#6366f1';
            subscribeButton.style.cursor = 'not-allowed';
            subscribeButton.style.opacity = '0.7';
            showToast('订阅成功', 'success');
          } else {
            throw new Error(response?.error || '订阅失败');
          }
        } catch (err) {
          console.error('[核桃FM] Failed to subscribe:', err);
          subscribeButton.textContent = '订阅';
          subscribeButton.disabled = false;
          showToast('订阅失败', 'error');
        }
      });
    }

    subscribeContainer.appendChild(subscribeButton);
    titleElement.appendChild(subscribeContainer);

    console.log('[核桃FM] Subscribe button injected');
  }

  // Add action buttons to episode cards
  function injectEpisodeButtons() {
    const episodeCards = document.querySelectorAll('a.card[href*="/episode/"]');

    episodeCards.forEach(card => {
      // Check if buttons already added
      if (card.dataset.xyzFmButtons) return;
      card.dataset.xyzFmButtons = 'true';

      // Find the time element (last line with publish info)
      const timeElement = card.querySelector('time, [class*="time"], [class*="date"]');
      if (!timeElement) {
        console.warn('[核桃FM] Time element not found in card');
        return;
      }

      // Create button container
      const buttonContainer = document.createElement('span');
      buttonContainer.className = 'xyz-fm-button-container';
      buttonContainer.style.cssText = `
        display: inline-flex;
        align-items: center;
        gap: 6px;
        margin-left: 12px;
        padding: 4px 8px 4px 6px;
        background: linear-gradient(135deg, #f0fdf4 0%, #ecfdf5 100%);
        border-radius: 16px;
        vertical-align: middle;
        border: 1px solid #d1fae5;
      `;

      // Prevent click event from bubbling to card
      buttonContainer.addEventListener('click', (e) => {
        e.stopPropagation();
        e.preventDefault();
      });

      // Create logo
      const logo = document.createElement('img');
      logo.src = chrome.runtime.getURL('images/logo.png');
      logo.alt = '核桃FM';
      logo.style.cssText = `
        width: 20px;
        height: 20px;
        border-radius: 4px;
      `;
      buttonContainer.appendChild(logo);

      // Create play button
      const playButton = document.createElement('button');
      playButton.className = 'xyz-fm-play-btn';
      playButton.setAttribute('aria-label', '立即播放');
      playButton.innerHTML = `
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M8 5v14l11-7L8 5z" fill="#6366f1"/>
        </svg>
      `;
      playButton.style.cssText = `
        width: 28px;
        height: 28px;
        background: white;
        border: 1px solid #e5e7eb;
        border-radius: 50%;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        padding: 0;
      `;

      playButton.addEventListener('mouseenter', () => {
        playButton.style.transform = 'scale(1.1)';
        playButton.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.15)';
      });

      playButton.addEventListener('mouseleave', () => {
        playButton.style.transform = 'scale(1)';
        playButton.style.boxShadow = '0 1px 3px rgba(0, 0, 0, 0.1)';
      });

      // Create add to queue button
      const addButton = document.createElement('button');
      addButton.className = 'xyz-fm-add-to-queue';
      addButton.setAttribute('aria-label', '加入播放列表');
      addButton.innerHTML = `
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" fill="#10b981"/>
        </svg>
      `;
      addButton.style.cssText = `
        width: 28px;
        height: 28px;
        background: white;
        border: 1px solid #e5e7eb;
        border-radius: 50%;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        padding: 0;
      `;

      addButton.addEventListener('mouseenter', () => {
        addButton.style.transform = 'scale(1.1)';
        addButton.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.15)';
      });

      addButton.addEventListener('mouseleave', () => {
        addButton.style.transform = 'scale(1)';
        addButton.style.boxShadow = '0 1px 3px rgba(0, 0, 0, 0.1)';
      });

      // Click handler for play button
      playButton.addEventListener('click', async (e) => {
        e.preventDefault();
        e.stopPropagation();

        console.log('[核桃FM] Play button clicked');

        const originalOpacity = playButton.style.opacity;
        playButton.style.opacity = '0.6';

        try {
          const episodeId = extractEpisodeIdFromCard(card);
          if (!episodeId) {
            throw new Error('无法获取节目ID');
          }

          // Fetch full episode data
          const episodeData = await fetchEpisodeData(episodeId);
          if (!episodeData) {
            throw new Error('无法获取节目数据');
          }

          // Play now
          const response = await chrome.runtime.sendMessage({
            type: 'xyz.playback.control',
            payload: {
              action: 'playNow',
              episode: episodeData,
            },
          });

          if (response && response.ok !== false) {
            console.log('[核桃FM] Playing in extension player');
            showToast('开始播放', 'success');
            setTimeout(() => {
              playButton.style.opacity = originalOpacity || '1';
            }, 500);
          } else {
            throw new Error(response?.error || '播放失败');
          }
        } catch (err) {
          console.error('[核桃FM] Failed to play:', err);
          showToast('播放失败', 'error');
          playButton.style.opacity = originalOpacity || '1';
        }
      });

      // Click handler for add to queue
      addButton.addEventListener('click', async (e) => {
        e.preventDefault();
        e.stopPropagation();

        console.log('[核桃FM] Add to queue clicked');

        const originalOpacity = addButton.style.opacity;
        addButton.style.opacity = '0.5';
        addButton.style.cursor = 'wait';

        try {
          const episodeId = extractEpisodeIdFromCard(card);
          if (!episodeId) {
            throw new Error('无法获取节目ID');
          }

          // Fetch full episode data
          const episodeData = await fetchEpisodeData(episodeId);
          if (!episodeData) {
            throw new Error('无法获取节目数据');
          }

          // Add to queue
          const response = await chrome.runtime.sendMessage({
            type: 'xyz.playback.control',
            payload: {
              action: 'enqueueNext',
              episode: episodeData,
            },
          });

          if (response && response.ok !== false) {
            console.log('[核桃FM] Added to queue');
            showToast('已加入播放列表', 'success');
            addButton.style.opacity = '0.3';
            setTimeout(() => {
              addButton.style.opacity = originalOpacity || '1';
              addButton.style.cursor = 'pointer';
            }, 500);
          } else {
            throw new Error(response?.error || '添加失败');
          }
        } catch (err) {
          console.error('[核桃FM] Failed to add to queue:', err);
          showToast('添加失败', 'error');
          addButton.style.opacity = originalOpacity || '1';
          addButton.style.cursor = 'pointer';
        }
      });

      // Add buttons to container
      buttonContainer.appendChild(playButton);
      buttonContainer.appendChild(addButton);

      // Insert after time element
      timeElement.parentNode.insertBefore(buttonContainer, timeElement.nextSibling);
    });
  }

  // Show toast notification
  function showToast(message, type = 'success') {
    // Remove existing toast if any
    const existingToast = document.getElementById('xyz-fm-toast');
    if (existingToast) {
      existingToast.remove();
    }

    // Create toast element
    const toast = document.createElement('div');
    toast.id = 'xyz-fm-toast';
    toast.textContent = message;

    const bgColor = type === 'success' ? '#10b981' : '#ef4444';
    toast.style.cssText = `
      position: fixed;
      top: 80px;
      left: 50%;
      transform: translateX(-50%);
      background: ${bgColor};
      color: white;
      padding: 12px 24px;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      z-index: 10000;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      animation: xyz-fm-toast-in 0.3s ease-out;
    `;

    // Add animation keyframes
    if (!document.getElementById('xyz-fm-toast-style')) {
      const style = document.createElement('style');
      style.id = 'xyz-fm-toast-style';
      style.textContent = `
        @keyframes xyz-fm-toast-in {
          from {
            opacity: 0;
            transform: translateX(-50%) translateY(-20px);
          }
          to {
            opacity: 1;
            transform: translateX(-50%) translateY(0);
          }
        }
        @keyframes xyz-fm-toast-out {
          from {
            opacity: 1;
            transform: translateX(-50%) translateY(0);
          }
          to {
            opacity: 0;
            transform: translateX(-50%) translateY(-20px);
          }
        }
      `;
      document.head.appendChild(style);
    }

    document.body.appendChild(toast);

    // Auto remove after 2 seconds
    setTimeout(() => {
      toast.style.animation = 'xyz-fm-toast-out 0.3s ease-out';
      setTimeout(() => {
        toast.remove();
      }, 300);
    }, 2000);
  }

  // Remove the fixed button from episode pages
  function removeFixedButton() {
    const fixedButton = document.getElementById('xyz-fm-button-container');
    if (fixedButton) {
      fixedButton.remove();
    }
  }

  // Initialize
  function initialize() {
    removeFixedButton();
    injectSubscribeButton();
    injectEpisodeButtons();
  }

  // Wait for page to load
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      setTimeout(initialize, 500);
    });
  } else {
    setTimeout(initialize, 500);
  }

  // Handle SPA navigation and dynamic content
  let lastUrl = location.href;
  const observer = new MutationObserver(() => {
    const currentUrl = location.href;
    if (currentUrl !== lastUrl) {
      lastUrl = currentUrl;
      setTimeout(initialize, 500);
    } else {
      // Re-inject buttons if new episodes appear
      injectEpisodeButtons();
    }
  });

  observer.observe(document.body, {
    subtree: true,
    childList: true
  });

})();
