// IPFS Chat Variables - using unique names to avoid conflicts
let ipfsInstance = null;
let ipfsPeerId = null;
let ipfsTopic = "liguana-chat";
let ipfsConnected = false;
// Removed unused retry variables

// Check if already initialized to prevent conflicts
if (window.ipfsChatInitialized) {
  console.log('IPFS Chat already initialized, skipping...');
} else {
  window.ipfsChatInitialized = true;

// Update connection status
function updateConnectionStatus(status, message) {
  const el = document.getElementById("connectionStatus");
  if (el) {
    el.textContent = message;
    el.className = `connection-status ${status}`;
  }
}

// Initialize IPFS with improved robustness (multi-star, retries, better session keys)
async function initializeIPFS() {
  try {
    const lm = window.languageManager;
    const t = (key, fallback) => (lm && typeof lm.getText === 'function' && lm.getText(key)) || fallback || key;
    updateConnectionStatus("connecting", t('connecting', 'Bağlanıyor...'));
    
    // Get topic from session storage (support both key variants)
    const getSess = (primary, legacy) => sessionStorage.getItem(primary) || sessionStorage.getItem(legacy);
    const sessionTopic = getSess('Lingoano_topic', 'liguana_topic');
    const sessionLanguage = getSess('Lingoano_language', 'liguana_language');
    const sessionLevel = getSess('Lingoano_level', 'liguana_level');
    
    if (sessionTopic) {
      ipfsTopic = sessionTopic;
      console.log("📋 Session topic kullanılıyor:", ipfsTopic);
    } else if (sessionLanguage && sessionLevel) {
      // Generate topic if not in session storage
      const salt = (window.env && window.env.LIGUANA_TOPIC_SALT) || 'ŞEBNEM';
      const combined = `${sessionLanguage}_${sessionLevel}_${salt}`;
      const encoder = new TextEncoder();
      const data = encoder.encode(combined);
      const hashBuffer = await crypto.subtle.digest('SHA-256', data);
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
      ipfsTopic = `liguana_${hashHex.substring(0, 16)}`;
      console.log("🔧 Topic oluşturuldu:", ipfsTopic);
    }

    // Candidate WebRTC-Star discovery servers (try in order)
    // Prefer custom relays defined via env (comma-separated full WSS URLs or multiaddr-friendly hostnames)
    let starCandidates = [];
    try {
      const envRelays = (window.env && window.env.WRTC_STAR_RELAYS) ? String(window.env.WRTC_STAR_RELAYS).trim() : '';
      if (envRelays) {
        const parts = envRelays.split(',').map(s => s.trim()).filter(Boolean);
        for (const p of parts) {
          if (p.startsWith('/')) {
            // Ensure suffix
            const ma = p.endsWith('/p2p-webrtc-star/') ? p : (p.endsWith('/p2p-webrtc-star') ? p + '/' : (p.endsWith('/') ? p + 'p2p-webrtc-star/' : p + '/p2p-webrtc-star/'));
            starCandidates.push(ma);
          } else if (p.startsWith('wss://')) {
            // Convert wss URL to multiaddr and ensure p2p-webrtc-star suffix
            try {
              const u = new URL(p);
              const host = u.hostname;
              const port = (u.port && Number(u.port)) ? Number(u.port) : 443;
              let path = u.pathname || '/';
              if (!/p2p-webrtc-star\/?$/.test(path)) {
                path = (path.endsWith('/') ? path : path + '/') + 'p2p-webrtc-star/';
              } else if (!path.endsWith('/')) {
                path = path + '/';
              }
              starCandidates.push(`/dns4/${host}/tcp/${port}/wss${path}`);
            } catch (_) {}
          }
        }
      }
    } catch (_) {}
    // Default public relays appended after custom ones
    starCandidates.push(
      "/dns4/wrtc-star1.par.dwebops.pub/tcp/443/wss/p2p-webrtc-star/",
      "/dns4/wrtc-star2.sjc.dwebops.pub/tcp/443/wss/p2p-webrtc-star/",
      "/dns4/webrtc-star.discovery.libp2p.io/tcp/443/wss/p2p-webrtc-star/"
    );

    // Try multiple stars with retries
    let instance = null;
    const timeoutMs = 30000; // 30s
    let lastError = null;
    for (let i = 0; i < starCandidates.length; i++) {
      const star = starCandidates[i];
      const ipfsConfig = {
        repo: 'liguana-ipfs-' + Math.random(),
        preload: { enabled: false }, // disable preload to avoid delegate/preload hosts
        config: {
          Addresses: {
            Swarm: [star],
            Announce: [star],
            Delegates: [] // avoid delegated routing endpoints in browser
          },
          Bootstrap: []
        }
      };
      updateConnectionStatus("connecting", `${t('connecting','Bağlanıyor...')} (IPFS ${i+1}/${starCandidates.length})`);
      console.log("🔄 IPFS starting with star:", star);
      try {
        const ipfsPromise = window.Ipfs.create(ipfsConfig);
        const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('IPFS Timeout')), timeoutMs));
        instance = await Promise.race([ipfsPromise, timeoutPromise]);
        if (instance) break;
      } catch (e) {
        console.warn(`IPFS init failed for star ${star}:`, e);
        lastError = e;
      }
    }
    
    if (!instance) {
        throw (lastError || new Error("IPFS init failed for all stars"));
    }

    ipfsInstance = instance;

    // Get peer ID
    const id = await ipfsInstance.id();
    ipfsPeerId = id.id;
    console.log("✅ IPFS başlatıldı. Peer ID:", ipfsPeerId);

    // Subscribe to topic with retry in case pubsub not ready yet
    let subscribed = false;
    for (let attempt = 1; attempt <= 3 && !subscribed; attempt++) {
      try {
        await ipfsInstance.pubsub.subscribe(ipfsTopic, handleMessage);
        subscribed = true;
      } catch (e) {
        console.warn(`PubSub subscribe retry ${attempt} failed:`, e);
        await new Promise(r => setTimeout(r, 500 * attempt));
      }
    }
    if (!subscribed) throw new Error('PubSub subscribe failed');
    console.log(`📡 ${ipfsTopic} konusuna abone olundu.`);

    // Hook libp2p peer events for visibility (best-effort)
    try {
      const lp = ipfsInstance.libp2p || (ipfsInstance._libp2p || null);
      if (lp && typeof lp.addEventListener === 'function') {
        lp.addEventListener('peer:connect', (evt) => console.log('🤝 IPFS peer connected:', evt && evt.detail ? evt.detail : evt));
        lp.addEventListener('peer:discovery', (evt) => console.log('🔎 IPFS peer discovered:', evt && evt.detail ? evt.detail : evt));
      }
    } catch (_) {}

    // Mark as connected
    ipfsConnected = true;
    updateConnectionStatus("connected", t('connected', 'Bağlandı'));

    // Enable message input
    const messageInput = document.getElementById("messageInput");
    const sendButton = document.getElementById("sendButton");
    
    if (messageInput) {
      messageInput.disabled = false;
      messageInput.placeholder = t('type-message', 'Mesajınızı yazın...');
    }
    
    if (sendButton) {
      sendButton.disabled = false;
    }

    // Add system message
    appendMessage(t('ipfs-chat-started', 'IPFS ağına bağlandınız. Sohbet başladı.'), "system");

    // Connected successfully

  } catch (error) {
    console.error("❌ IPFS error:", error);
    updateConnectionStatus("error", (window.languageManager && window.languageManager.getText('error')) || 'Hata');
    // Re-throw the error to be caught by the protocol selector
    throw error;
  }
}

// Removed unused error helpers; errors bubble up to selector for fallback

// Handle incoming messages
function handleMessage(msg) {
  try {
    // Use msg.from to get the sender's PeerId. This is more reliable.
    const senderId = msg.from;

    // Do not display own messages
    if (senderId === ipfsPeerId) {
      console.log("🔄 Kendi mesajım filtrelendi (msg.from kullanıldı).");
      return;
    }

    const decoded = new TextDecoder().decode(msg.data);
    const parsed = JSON.parse(decoded);

    console.log(`✅ Karşı taraftan (${senderId}) mesaj alındı:`, parsed);
    appendMessage(parsed.text, "received");
    
  } catch (err) {
    console.error("Mesaj çözümleme hatası:", err, msg);
  }
}

// Send message
async function sendMessageInternal(text) {
  if (!text || !text.trim()) {
    console.warn("Mesaj gönderilemez: Metin boş");
    return false;
  }

  // Real IPFS mode
  if (!ipfsInstance || !ipfsConnected) {
    console.warn("Mesaj gönderilemez: IPFS bağlı değil");
    return false;
  }

  // The sender ID is part of the message envelope (msg.from), so it's not needed in the payload.
  const message = {
    text: text.trim(),
    timestamp: Date.now(),
    topic: ipfsTopic
  };

  try {
    const messageData = new TextEncoder().encode(JSON.stringify(message));
    await ipfsInstance.pubsub.publish(ipfsTopic, messageData);
    
    console.log("📤 Mesaj gönderildi:", message);
    appendMessage(text.trim(), "sent");
    return true;
    
  } catch (err) {
    console.error("❌ Mesaj gönderilemedi:", err);
    appendMessage("Mesaj gönderilemedi. Bağlantınızı kontrol edin.", "system");
    return false;
  }
}

// Add message to chat window
function appendMessage(text, type) {
  const chatMessages = document.getElementById("chatMessages");
  if (!chatMessages) {
    console.error("Chat messages container bulunamadı");
    return;
  }

  const messageEl = document.createElement("div");
  messageEl.className = `message ${type}`;
  messageEl.textContent = text;
  
  // Add timestamp for non-system messages
  if (type !== "system") {
    const timestamp = new Date().toLocaleTimeString('tr-TR', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
    messageEl.setAttribute('data-time', timestamp);
  }
  
  chatMessages.appendChild(messageEl);
  
  // Auto-scroll to bottom
  chatMessages.scrollTop = chatMessages.scrollHeight;
}

// Make appendMessage globally available
window.appendMessage = appendMessage;

// Handle form submission
function setupMessageForm() {
  const messageForm = document.getElementById("messageForm");
  const messageInput = document.getElementById("messageInput");
  
  if (messageForm && messageInput) {
    // Handle form submission
    messageForm.addEventListener("submit", async function(e) {
      e.preventDefault();
      
      const text = messageInput.value.trim();
      if (text) {
        const success = await sendMessageInternal(text);
        if (success) {
          messageInput.value = "";
        }
      }
    });
    
    // Handle Enter key - directly call the same logic instead of dispatching event
    messageInput.addEventListener("keypress", async function(e) {
      if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        
        const text = messageInput.value.trim();
        if (text) {
          const success = await sendMessageInternal(text);
          if (success) {
            messageInput.value = "";
          }
        }
      }
    });
    
    console.log("✅ Form event listeners kuruldu");
  } else {
    console.warn("⚠️ Form veya input elementi bulunamadı");
  }
}

// Cleanup on page unload
function cleanup() {
  if (ipfsInstance) {
    try {
      ipfsInstance.pubsub.unsubscribe(ipfsTopic);
      ipfsInstance.stop();
    } catch (err) {
      console.error("Cleanup hatası:", err);
    }
  }
}

// Make cleanup globally available
window.cleanup = cleanup;

// Initialize IPFS protocol
function initializeIPFSProtocol() {
  console.log("🦎 Lingoano Chat IPFS başlatılıyor...");
  
  // Setup form handlers
  setupMessageForm();
  
  // Start IPFS and let the promise be handled by the caller (protocol_selector)
  return initializeIPFS();
}

// Auto-initialize if not loaded by protocol selector
if (!window.protocolSelectorLoaded) {
  document.addEventListener('DOMContentLoaded', function() {
    initializeIPFSProtocol();
    window.addEventListener('beforeunload', cleanup);
  });
}

// Make initialization function globally available
window.initializeIPFSProtocol = initializeIPFSProtocol;

// Make sendMessage globally available for backward compatibility
window.sendMessage = async function() {
  const messageInput = document.getElementById("messageInput");
  if (messageInput) {
    const text = messageInput.value.trim();
    if (text) {
      const success = await sendMessageInternal(text);
      if (success) {
        messageInput.value = "";
      }
    }
  }
};

} // Close the if statement from the beginning
