// WebRTC-based chat system for Lingoano
// Check if already initialized to prevent conflicts
if (window.webrtcChatInitialized) {
  console.log('WebRTC Chat already initialized, skipping...');
} else {
  window.webrtcChatInitialized = true;

let webrtcPeerConnection = null;
let webrtcDataChannel = null;
let webrtcConnected = false;
let webrtcTopic = "liguana-chat";
let webrtcUserId = null;
let signalingSocket = null; // WebSocket for signaling
let isOfferer = false;
let pendingIce = [];

// Initialize WebRTC with signaling
function initializeWebRTC() {
    return new Promise(async (resolve, reject) => {
        try {
            const connectionTimeout = setTimeout(() => {
                reject(new Error("WebRTC bağlantısı zaman aşımına uğradı."));
            }, 25000); // 25-second timeout for the entire process

            console.log("🌐 WebRTC başlatılıyor...");
            
            const getSess = (p,l) => sessionStorage.getItem(p) || sessionStorage.getItem(l);
            const sessionTopic = getSess('Lingoano_topic','liguana_topic');
            if (sessionTopic) {
                webrtcTopic = sessionTopic;
            } else {
                return reject(new Error("WebRTC için oturum konusu (topic) bulunamadı."));
            }

            webrtcUserId = 'webrtc_user_' + Math.random().toString(36).substr(2, 9);
            const role = (getSess('Lingoano_role','liguana_role') || '').toLowerCase();
            isOfferer = (role === 'host');
            
            signalingSocket = new WebSocket(`wss://lingoano.onrender.com/liguanadinlemeserver/chat`);

            signalingSocket.onclose = () => reject(new Error("Sinyal sunucusu bağlantısı kapandı."));
            signalingSocket.onerror = (error) => reject(new Error("Sinyal sunucusuna bağlanılamadı."));
            
            const iceServers = [
                { urls: [
                    'stun:stun.l.google.com:19302',
                    'stun:stun1.l.google.com:19302',
                    'stun:global.stun.twilio.com:3478',
                    'stun:stun.stunprotocol.org:3478'
                ]}
            ];
            try {
                const cfg = (window.env || {});
                if (cfg.TURN_URL && cfg.TURN_USER && cfg.TURN_PASS) {
                    iceServers.push({ urls: cfg.TURN_URL, username: cfg.TURN_USER, credential: cfg.TURN_PASS });
                }
            } catch (_) {}
            webrtcPeerConnection = new RTCPeerConnection({ iceServers });

            const setupDataChannelEvents = (channel) => {
                channel.onopen = () => {
                    console.log("✅ WebRTC Data Channel açıldı");
                    webrtcConnected = true;
                    clearTimeout(connectionTimeout);
                    const messageInput = document.getElementById("messageInput");
                    const sendButton = document.getElementById("sendButton");
                    const lm = window.languageManager;
                    const t = (key, fallback) => (lm && typeof lm.getText === 'function' && lm.getText(key)) || fallback || key;
                    if (messageInput) {
                        messageInput.disabled = false;
                        messageInput.placeholder = `WebRTC - ${t('type-message', 'Mesajınızı yazın...')}`;
                    }
                    if (sendButton) {
                        sendButton.disabled = false;
                    }
                    resolve(); // SUCCESS
                };
                channel.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);
                        if (data.userId !== webrtcUserId) {
                            appendMessage(data.text, "received");
                        }
                    } catch (err) {
                        appendMessage(event.data, "received");
                    }
                };
                 channel.onerror = (error) => console.error("❌ WebRTC Data Channel hatası:", error);
                 channel.onclose = () => {
                    webrtcConnected = false;
                    appendMessage("WebRTC bağlantısı kesildi.", "system");
                 };
            };

            webrtcPeerConnection.ondatachannel = (event) => {
                webrtcDataChannel = event.channel;
                setupDataChannelEvents(webrtcDataChannel);
            };

            webrtcPeerConnection.onicecandidate = (event) => {
                if (event.candidate) {
                    const msg = { type: 'candidate', candidate: event.candidate };
                    if (signalingSocket && signalingSocket.readyState === WebSocket.OPEN) {
                        signalingSocket.send(JSON.stringify(msg));
                    }
                }
            };

            webrtcPeerConnection.onnegotiationneeded = async () => {
                try {
                    if (isOfferer && webrtcPeerConnection.signalingState !== 'have-local-offer') {
                        const offer = await webrtcPeerConnection.createOffer();
                        await webrtcPeerConnection.setLocalDescription(offer);
                        signalingSocket.send(JSON.stringify(offer));
                    }
                } catch (e) { console.warn('negotiationneeded error', e); }
            };
            
            signalingSocket.onmessage = async (event) => {
                const data = JSON.parse(event.data);
                if (data.type === 'offer') {
                    await webrtcPeerConnection.setRemoteDescription(new RTCSessionDescription(data));
                    const answer = await webrtcPeerConnection.createAnswer();
                    await webrtcPeerConnection.setLocalDescription(answer);
                    signalingSocket.send(JSON.stringify(answer));
                } else if (data.type === 'answer') {
                    await webrtcPeerConnection.setRemoteDescription(new RTCSessionDescription(data));
                } else if (data.type === 'candidate') {
                    try {
                        await webrtcPeerConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
                    } catch (e) { console.warn('addIceCandidate error', e); }
                } else if (data.type === 'user_joined' && webrtcPeerConnection.connectionState !== 'connected') {
                    if (isOfferer && !webrtcDataChannel) {
                        webrtcDataChannel = webrtcPeerConnection.createDataChannel('chat');
                        setupDataChannelEvents(webrtcDataChannel);
                        const offer = await webrtcPeerConnection.createOffer();
                        await webrtcPeerConnection.setLocalDescription(offer);
                        signalingSocket.send(JSON.stringify(offer));
                    }
                }
            };

            signalingSocket.onopen = () => {
                console.log("✅ Sinyal sunucusuna bağlandı.");
                signalingSocket.send(JSON.stringify({ type: 'join', topic: webrtcTopic, userId: webrtcUserId }));
            };

        } catch (error) {
            console.error("❌ WebRTC başlatma hatası:", error);
            reject(error);
        }
    });
}

// Removed unused handleWebRTCError (errors are handled via promise rejections)

// Show WebRTC connection error
function enableWebRTCDemoMode() {
  const messageInput = document.getElementById("messageInput");
  const sendButton = document.getElementById("sendButton");
  
  const lm = window.languageManager;
  const t = (key, fallback) => (lm && typeof lm.getText === 'function' && lm.getText(key)) || fallback || key;
  if (messageInput) {
    messageInput.disabled = true;
    messageInput.placeholder = `WebRTC - ${t('connection-error-placeholder', 'Bağlantı hatası')}`;
  }
  
  if (sendButton) {
    sendButton.disabled = true;
  }
  
  appendMessage("WebRTC bağlantısı kurulamadı. Lütfen ağ bağlantınızı kontrol edin.", "system");
}

// Setup data channel
function setupDataChannel() {
  webrtcDataChannel.onopen = () => {
    console.log("✅ WebRTC Data Channel açıldı");
    webrtcConnected = true;
    
    const messageInput = document.getElementById("messageInput");
    const sendButton = document.getElementById("sendButton");
    
    const lm = window.languageManager;
    const t = (key, fallback) => (lm && typeof lm.getText === 'function' && lm.getText(key)) || fallback || key;
    if (messageInput) {
      messageInput.disabled = false;
      messageInput.placeholder = `WebRTC - ${t('type-message', 'Mesajınızı yazın...')}`;
    }
    
    if (sendButton) {
      sendButton.disabled = false;
    }
    
    appendMessage("WebRTC peer-to-peer bağlantısı aktif!", "system");
  };

  webrtcDataChannel.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      console.log("📨 WebRTC mesaj alındı:", data);
      
      if (data.userId !== webrtcUserId) {
        appendMessage(data.text, "received");
      }
    } catch (err) {
      console.error("WebRTC mesaj çözümleme hatası:", err);
      appendMessage(event.data, "received");
    }
  };

  webrtcDataChannel.onerror = (error) => {
    console.error("❌ WebRTC Data Channel hatası:", error);
    appendMessage("WebRTC bağlantı hatası oluştu.", "system");
  };

  webrtcDataChannel.onclose = () => {
    console.log("WebRTC Data Channel kapandı");
    webrtcConnected = false;
    appendMessage("WebRTC bağlantısı kesildi.", "system");
  };
}

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



  // Real WebRTC mode
  if (!webrtcDataChannel || webrtcDataChannel.readyState !== 'open') {
    console.warn("Mesaj gönderilemez: WebRTC bağlı değil");
    return false;
  }

  try {
    const message = {
      userId: webrtcUserId,
      text: text.trim(),
      timestamp: Date.now(),
      topic: webrtcTopic
    };
    
    webrtcDataChannel.send(JSON.stringify(message));
    console.log("📤 WebRTC mesaj gönderildi:", message);
    appendMessage(text.trim(), "sent");
    return true;
    
  } catch (err) {
    console.error("❌ WebRTC 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
    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("✅ WebRTC form event listeners kuruldu");
  } else {
    console.warn("⚠️ Form veya input elementi bulunamadı");
  }
}

// Cleanup on page unload
function cleanup() {
  if (webrtcDataChannel) {
    try {
      webrtcDataChannel.close();
    } catch (err) {
      console.error("WebRTC cleanup hatası:", err);
    }
  }
  
  if (webrtcPeerConnection) {
    try {
      webrtcPeerConnection.close();
    } catch (err) {
      console.error("WebRTC peer connection cleanup hatası:", err);
    }
  }
}

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

// Initialize WebRTC protocol
async function initializeWebRTCProtocol() {
  console.log("🦎 Lingoano Chat WebRTC başlatılıyor...");
  setupMessageForm();
  await initializeWebRTC();
  
  // Welcome message is now sent from the data channel onopen event
}

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

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

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