// Content script for XiaoYuZhou episode pages
// Adds "Add to Queue" button on episode pages

(function() {
  'use strict';

  const EPISODE_PATH_REGEX = /^\/episode\/([a-f0-9]+)/;

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

  // Extract episode data from __NEXT_DATA__
  function extractEpisodeData() {
    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 episode = nextData?.props?.pageProps?.episode;

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

      // Transform to standard Episode format
      return {
        id: episode.eid || episode.id,
        title: episode.title || '',
        description: episode.description || episode.shownotes || '',
        pubDate: episode.pubDate ? new Date(episode.pubDate).getTime() : Date.now(),
        duration: episode.duration || 0,
        audioUrl: episode.enclosure?.url || episode.media?.source?.url || '',
        image: episode.podcast?.image?.picUrl || episode.image?.picUrl || '',
        podcastId: episode.podcast?.pid || episode.podcast?.id || '',
        podcastTitle: episode.podcast?.title || '',
        source: 'xiaoyuzhou',
        sourceRef: episode.eid || episode.id,
      };
    } catch (err) {
      console.error('[核桃FM] Failed to parse episode data:', err);
      return null;
    }
  }

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

    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);
    `;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 2000);
  }

  // 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;
    }
  }

  // Inject subscribe button after podcast title
  async function injectSubscribeButton() {
    if (document.getElementById('xyz-fm-subscribe-btn')) return;

    const episodeData = extractEpisodeData();
    console.log('[核桃FM] Episode data:', episodeData);
    if (!episodeData || !episodeData.podcastId) {
      console.log('[核桃FM] No episode data or podcastId');
      return;
    }

    console.log('[核桃FM] Checking subscription for:', episodeData.podcastId, episodeData.podcastTitle);
    const isSubscribed = await isPodcastSubscribed(episodeData.podcastId, episodeData.podcastTitle);
    console.log('[核桃FM] Is subscribed:', isSubscribed);

    const podcastTitleDiv = document.querySelector('.podcast-title');
    if (!podcastTitleDiv) return;

    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: {
              id: episodeData.podcastId,
              title: episodeData.podcastTitle,
              image: episodeData.image,
              source: 'xiaoyuzhou',
              sourceRef: episodeData.podcastId,
            },
          });

          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);
    podcastTitleDiv.appendChild(subscribeContainer);
  }

  // Create and inject the button
  function injectButton() {
    const episodeId = getEpisodeIdFromUrl();
    if (!episodeId) return;

    if (document.getElementById('xyz-fm-button-container')) return;

    // Create button container - fixed position at bottom right
    const buttonContainer = document.createElement('div');
    buttonContainer.id = 'xyz-fm-button-container';
    buttonContainer.style.cssText = `
      position: fixed;
      bottom: 15px;
      right: 50%;
      transform: translateX(200px);
      z-index: 9999;
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 4px 8px 4px 6px;
      background: linear-gradient(135deg, #f0fdf4 0%, #ecfdf5 100%);
      border-radius: 16px;
      border: 1px solid #d1fae5;
    `;

    // 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.setAttribute('aria-label', '立即播放');
    playButton.innerHTML = `
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
        <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('click', async () => {
      try {
        const episodeData = extractEpisodeData();
        if (!episodeData) throw new Error('无法获取节目数据');

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

        if (response && response.ok !== false) {
          showToast('开始播放', 'success');
        } else {
          throw new Error(response?.error || '播放失败');
        }
      } catch (err) {
        console.error('[核桃FM] Failed to play:', err);
        showToast('播放失败', 'error');
      }
    });

    // Create add to queue button
    const addButton = document.createElement('button');
    addButton.setAttribute('aria-label', '加入播放列表');
    addButton.innerHTML = `
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
        <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('click', async () => {
      try {
        const episodeData = extractEpisodeData();
        if (!episodeData) throw new Error('无法获取节目数据');

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

        if (response && response.ok !== false) {
          showToast('已加入播放列表', 'success');
        } else {
          throw new Error(response?.error || '添加失败');
        }
      } catch (err) {
        console.error('[核桃FM] Failed to add to queue:', err);
        showToast('添加失败', 'error');
      }
    });

    buttonContainer.appendChild(playButton);
    buttonContainer.appendChild(addButton);
    document.body.appendChild(buttonContainer);

    console.log('[核桃FM] Button injected successfully');
  }

  // Initialize
  function initialize() {
    injectButton();
    injectSubscribeButton();
  }

  // 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);
    }
  });

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

})();
