/**
 * KuponMarket - Trendyol Content Handler
 * tgoyemek.com ve trendyol.com'da çalışır (ISOLATED world)
 * Inject script ile background arasında köprü görevi görür
 */

(function() {
  'use strict';

  const api = typeof chrome !== 'undefined' ? chrome : (typeof browser !== 'undefined' ? browser : null);
  if (api && !window.chrome) window.chrome = api;

  console.log('[KM-TGO] Content handler loaded');

  const serviceType = window.location.hostname.includes('tgoyemek') ? 'yemek' : 'market';

  // Popup blocker CSS
  const style = document.createElement('style');
  style.id = 'km-tgo-popup-blocker';
  style.textContent = `
    [role="dialog"]:has(h2:contains("Son Bir Adım Kaldı")) { display: none !important; }
    div[class*="fixed"][class*="inset-0"]:has([role="dialog"]) { display: none !important; }
    div[class*="fixed bottom-0"],
    div[class*="fixed"][class*="bottom-0"],
    div:has(> div > button:contains("Reddet")),
    div:has(> div > button:contains("Kabul Et")) { display: none !important; }
  `;
  (document.head || document.documentElement).appendChild(style);

  // Popup hide via DOM
  const hidePopup = () => {
    const dialogs = document.querySelectorAll('[role="dialog"]');
    dialogs.forEach(dialog => {
      const text = dialog.textContent || '';
      if (text.includes('Son Bir Adım Kaldı') || text.includes('Ad, soyad ve telefon numarası') || text.includes('teyit etmemiz gerekiyor')) {
        const parent = dialog.parentElement;
        if (parent) parent.style.display = 'none';
        dialog.style.display = 'none';
      }
    });

    document.querySelectorAll('div').forEach(div => {
      const text = div.textContent || '';
      if ((text.includes('Reddet') && text.includes('Kabul Et')) ||
          text.includes('SANA ÖZEL BİR DENEYİM İÇİN ÇALIŞIYORUZ') ||
          text.includes('çerez kullanıyoruz')) {
        div.style.display = 'none';
        const parent = div.parentElement;
        if (parent && (parent.style.position === 'fixed' || parent.classList.contains('fixed'))) {
          parent.style.display = 'none';
        }
      }
    });
  };

  setInterval(hidePopup, 500);
  const observer = new MutationObserver(hidePopup);
  observer.observe(document.documentElement, { childList: true, subtree: true });

  // PWA manifest kaldır
  const manifestLinks = document.querySelectorAll('link[rel="manifest"]');
  manifestLinks.forEach(link => link.remove());

  // Inject scripts
  injectScript('src/tgo/tgoInterceptor.js');
  injectScript('src/tgo/tgoCartPromo.js');

  function injectScript(scriptPath) {
    const script = document.createElement('script');
    script.src = chrome.runtime.getURL(scriptPath);
    script.type = 'text/javascript';
    (document.head || document.documentElement).appendChild(script);
    script.onload = () => script.remove();
  }

  // Login status check (cookies API background'dan geçer)
  checkLoginStatus();

  async function checkLoginStatus() {
    try {
      const response = await chrome.runtime.sendMessage({
        action: 'GET_COOKIES',
        data: { url: window.location.href, name: 'tgo-token' }
      });
      if (response && response.cookie && response.cookie.value) {
        console.log('[KM-TGO] Trendyol oturum açık');
      }
    } catch (error) {}
  }

  // Background'a message listener
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'tyProxyRequest') {
      chrome.runtime.sendMessage(request, (response) => {
        sendResponse(response);
      });
      return true;
    }

    if (request.action === 'TRENDYOL_LOGIN_COMPLETE') {
      setTimeout(() => window.location.reload(), 500);
      sendResponse({ success: true });
    }
    return true;
  });

  // Inject script'ten gelen mesajları background'a ilet
  window.addEventListener('message', async (event) => {
    if (event.source !== window) return;
    if (!event.data || event.data.source !== 'KM_TGO_INJECT') return;

    if (event.data.action === 'tySnapshotUpdate') {
      try {
        const incoming = event.data.snapshot || {};
        const cur = await chrome.storage.local.get(['tySnapshot']);
        const merged = Object.assign({}, cur.tySnapshot || {}, incoming, { _ts: Date.now() });
        await chrome.storage.local.set({ tySnapshot: merged });
      } catch (e) {}
      return;
    }

    if (event.data.action !== 'tyProxyRequest') return;

    const { messageId, url, method, headers, body } = event.data;

    try {
      const response = await chrome.runtime.sendMessage({
        action: 'tyProxyRequest',
        url: url,
        method: method,
        headers: headers,
        body: body
      });

      window.postMessage({
        source: 'KM_TGO_CONTENT',
        messageId: messageId,
        success: response.success,
        status: response.status,
        statusText: response.statusText,
        headers: response.headers,
        data: response.data,
        error: response.error
      }, '*');
    } catch (error) {
      window.postMessage({
        source: 'KM_TGO_CONTENT',
        messageId: messageId,
        success: false,
        error: error.message
      }, '*');
    }
  });

})();
