// Modal content configuration
// This file fetches content from the backend API and patches modals dynamically
window.WPLACE_INFO = {
  // Default fallback content (used if API fails)
  modal: {
    overview: {
      title_en: "Overview",
      title_zh: "概述",
      videoUrl: "https://www.youtube.com/embed/xOXtd-WzRxA?si=fHz8Z6ecXGYrDhkN"
    },
    paintFaster: {
      title_en: "How to paint faster",
      title_zh: "如何画得更快？",
      mobile_en: "When painting, click on the button on the top right corner of the screen. This will lock the screen but it'll also enable painting by moving your finger over the map.",
      mobile_zh: "在绘制时候按住按钮屏幕右上角。这将锁定屏幕，但也可以通过在地图上移动手指来绘画.",
      desktop_en: "Hold SPACE and move your cursor over the map.",
      desktop_zh: "按住空格并且移动鼠标."
    },
    mapLagging: {
      title_en: "My map is lagging",
      title_zh: "地图卡顿",
      text_en: "Follow the instructions to enable hardware acceleration:",
      text_zh: "请按照说明启用硬件加速：",
      link: "https://help.constructiononline.com/en/scheduling-webgl-and-hardware-acceleration"
    },
    rules: {
      title_en: "Rules",
      title_zh: "规则",
      badge_en: "Important",
      badge_zh: "重要",
      items: [
        { text_en: "📜 All users are responsible for the content they post. The platform reserves the right of final interpretation.", text_zh: "📜 所有用户对其发布的内容负责。平台保留最终解释权。" },
        { text_en: "🛑 Any violation may result in immediate removal of content and permanent ban of the account", text_zh: "🛑 任何违规行为可能导致内容立即删除和账户永久封禁" },
        { text_en: "😈 Do not paint over other artworks using random colors or patterns just to mess things up", text_zh: "😈 请勿使用随机颜色或图案覆盖其他作品" },
        { text_en: "🙅 Disclosing other's personal information is not allowed", text_zh: "🙅 不允许泄露他人个人信息" }
      ],
      footer_en: "Violations of these rules may result in suspension of your account.",
      footer_zh: "违反会导致你被封禁。"
    },
    footer: {
      email: "contact@wplace.live",
      discord: { url: "https://discord.gg/ZRC4DnP9Z2", text_en: "Feedback and bugs", text_zh: "反馈和错误报告" },
      github: { url: "https://github.com/openplaceteam", text_en: "Github", text_zh: "Github" },
      instagram: { url: "https://www.instagram.com/wplace.live/", text_en: "Instagram", text_zh: "Instagram" },
      terms: { url: "https://wplace.live/terms/terms-of-service", text_en: "Terms", text_zh: "条款" },
      privacy: { url: "https://wplace.live/terms/privacy", text_en: "Privacy", text_zh: "隐私" }
    }
  },

  // Loaded content from API
  loadedContent: {},
  contentLoaded: false
};

// Function to get current locale
function getCurrentLocale() {
  return localStorage.getItem('locale') || 'en';
}

// Function to load content from API
async function loadContentFromAPI() {
  try {
    const locale = getCurrentLocale();
    const response = await fetch(`/api/site-content?locale=${locale}`);

    if (!response.ok) {
      console.warn('[WPLACE_INFO] Failed to load content from API, using defaults');
      return false;
    }

    const data = await response.json();
    window.WPLACE_INFO.loadedContent = data.content || {};
    window.WPLACE_INFO.contentLoaded = true;

    console.log('[WPLACE_INFO] Content loaded from API:', Object.keys(window.WPLACE_INFO.loadedContent).length, 'items');
    return true;
  } catch (error) {
    console.error('[WPLACE_INFO] Error loading content from API:', error);
    return false;
  }
}

// Helper function to get value from API content or fallback
function getContent(key, locale = 'en') {
  const apiKey = key;

  // Try to get from loaded API content first
  if (window.WPLACE_INFO.contentLoaded && window.WPLACE_INFO.loadedContent[apiKey]) {
    return window.WPLACE_INFO.loadedContent[apiKey];
  }

  // Fallback to hardcoded defaults
  const keys = key.split('.');
  let obj = window.WPLACE_INFO.modal;

  for (let i = 1; i < keys.length; i++) { // Skip 'modal' prefix
    obj = obj[keys[i]];
    if (!obj) return '';
  }

  // Try localized version first
  const localizedKey = keys[keys.length - 1] + '_' + locale;
  if (obj && obj[localizedKey]) return obj[localizedKey];

  return obj || '';
}

// Function to parse rule items from API content
function getRuleItems(locale = 'en') {
  const items = [];
  let index = 0;

  while (true) {
    const item = getContent(`modal.rules.item.${index}`, locale);
    if (!item) break;
    items.push(item);
    index++;
  }

  // Fallback to default if no items found
  if (items.length === 0 && window.WPLACE_INFO.modal.rules.items) {
    return window.WPLACE_INFO.modal.rules.items.map(i => i['text_' + locale] || i.text_en);
  }

  return items;
}

// Function to patch the info modal
function patchInfoModal(modal) {
  const locale = getCurrentLocale();

  // Find the modal content container
  const modalBox = modal.querySelector('.modal-box.sm\\:max-w-5xl');
  if (!modalBox) return;

  // Check if this is the info/welcome modal
  const hasLogo = modalBox.querySelector('img[alt*="logo" i]');
  const hasOverview = modalBox.textContent.includes('Overview') || modalBox.textContent.includes('概述');

  if (!hasLogo && !hasOverview) return;

  console.log('[WPLACE_INFO] Patching info modal with custom content');

  // Find all sections and update them
  const sections = modalBox.querySelectorAll('section');

  sections.forEach(section => {
    // Patch "How to paint faster" section
    const paintFasterTitle = section.querySelector('h3');
    if (paintFasterTitle && (paintFasterTitle.textContent.includes('paint faster') || paintFasterTitle.textContent.includes('画得更快'))) {
      paintFasterTitle.textContent = getContent('modal.paintFaster.title', locale);

      const mobileText = section.querySelector('.not-touchscreen\\:hidden');
      if (mobileText) {
        const textNodes = Array.from(mobileText.childNodes).filter(n => n.nodeType === 3);
        textNodes.forEach(node => {
          if (node.textContent.trim()) {
            node.textContent = getContent('modal.paintFaster.mobile', locale);
          }
        });
      }

      const desktopText = section.querySelector('.touchscreen\\:hidden');
      if (desktopText) {
        const textNodes = Array.from(desktopText.childNodes).filter(n => n.nodeType === 3);
        textNodes.forEach(node => {
          if (node.textContent.trim()) {
            node.textContent = getContent('modal.paintFaster.desktop', locale);
          }
        });
      }
    }

    // Patch "My map is lagging" section
    const laggingTitle = section.querySelector('h3');
    if (laggingTitle && (laggingTitle.textContent.includes('lagging') || laggingTitle.textContent.includes('卡顿'))) {
      laggingTitle.textContent = getContent('modal.mapLagging.title', locale);

      const text = section.querySelector('p');
      if (text) {
        const link = text.querySelector('a');
        if (link) {
          link.href = getContent('modal.mapLagging.link', locale);
          text.childNodes.forEach(node => {
            if (node.nodeType === 3 && node.textContent.trim()) {
              node.textContent = getContent('modal.mapLagging.text', locale) + ' ';
            }
          });
        }
      }
    }

    // Patch Rules section
    const rulesHeader = section.querySelector('h3');
    if (rulesHeader && (rulesHeader.textContent.includes('Rules') || rulesHeader.textContent.includes('规则'))) {
      rulesHeader.textContent = getContent('modal.rules.title', locale);

      const badge = rulesHeader.querySelector('.badge');
      if (badge) badge.textContent = getContent('modal.rules.badge', locale);

      const rulesList = section.querySelector('ul');
      if (rulesList) {
        const ruleItems = rulesList.querySelectorAll('li');
        const contentItems = getRuleItems(locale);

        ruleItems.forEach((item, index) => {
          if (contentItems[index]) {
            item.textContent = contentItems[index];
          }
        });
      }

      const footer = section.querySelector('p.text-base-content\\/80');
      if (footer) {
        footer.textContent = getContent('modal.rules.footer', locale);
      }
    }
  });

  // Patch footer links
  const footerSection = modalBox.querySelector('section.text-center:last-of-type');
  if (footerSection) {
    const emailLink = footerSection.querySelector('a[href^="mailto:"]');
    if (emailLink) {
      const email = getContent('modal.footer.email', locale);
      emailLink.href = 'mailto:' + email;
    }

    const termsLink = footerSection.querySelector('a[href*="terms-of-service"], a[href*="terms"]');
    if (termsLink) {
      termsLink.href = getContent('modal.footer.terms.url', locale);
      const termsText = getContent('modal.footer.terms.text', locale);
      if (termsText) termsLink.textContent = termsText;
    }

    const privacyLink = footerSection.querySelector('a[href*="privacy"]');
    if (privacyLink) {
      privacyLink.href = getContent('modal.footer.privacy.url', locale);
      const privacyText = getContent('modal.footer.privacy.text', locale);
      if (privacyText) privacyLink.textContent = privacyText;
    }

    const discordLinks = footerSection.querySelectorAll('a[href*="discord"]');
    discordLinks.forEach(link => {
      link.href = getContent('modal.footer.discord.url', locale);
    });

    const githubLink = footerSection.querySelector('a[href*="github"]');
    if (githubLink) {
      githubLink.href = getContent('modal.footer.github.url', locale);
    }

    const instagramLink = footerSection.querySelector('a[href*="instagram"]');
    if (instagramLink) {
      instagramLink.href = getContent('modal.footer.instagram.url', locale);
    }
  }

  // Patch video URL
  const iframe = modalBox.querySelector('iframe[src*="youtube"]');
  if (iframe) {
    const videoUrl = getContent('modal.overview.videoUrl', locale);
    if (videoUrl) iframe.src = videoUrl;
  }
}

// Use MutationObserver to watch for modal being added to DOM
const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    mutation.addedNodes.forEach((node) => {
      if (node.nodeType === 1) {
        if (node.matches && node.matches('dialog.modal')) {
          patchInfoModal(node);
        } else if (node.querySelectorAll) {
          const modals = node.querySelectorAll('dialog.modal');
          modals.forEach(modal => patchInfoModal(modal));
        }
      }
    });
  });
});

// Initialize on page load
(async function() {
  'use strict';

  // Load content from API
  await loadContentFromAPI();

  // Start observing when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      observer.observe(document.body, { childList: true, subtree: true });
      document.querySelectorAll('dialog.modal').forEach(modal => patchInfoModal(modal));
    });
  } else {
    observer.observe(document.body, { childList: true, subtree: true });
    document.querySelectorAll('dialog.modal').forEach(modal => patchInfoModal(modal));
  }

  console.log('[WPLACE_INFO] Monkey patch initialized');
})();
