// import { useEffect, useRef } from "react";
// import { useNavigate } from "react-router-dom";

// const JitsiMeeting = ({ roomName, displayName }) => {
//     const containerRef = useRef(null);
//     const apiRef = useRef(null);
//     const navigate = useNavigate();

//     const getLocation = () =>
//         new Promise((resolve) => {
//             navigator.geolocation.getCurrentPosition(
//                 (pos) => {
//                     const { latitude, longitude } = pos.coords;
//                     resolve(`Lat: ${latitude.toFixed(2)}, Lng: ${longitude.toFixed(2)}`);
//                 },
//                 () => resolve("Location: Off"),
//                 { timeout: 3000 }
//             );
//         });

//     const parseBrowser = (userAgent) => {
//         const browserRegex = /(firefox|msie|trident|chrome|safari|opera|edg)\/?\s*(\d+)/i;
//         const match = userAgent.match(browserRegex);
//         if (match) {
//             const browser = match[1].toLowerCase();
//             const version = match[2];
//             return `${browser.charAt(0).toUpperCase() + browser.slice(1)} ${version}`;
//         }
//         return "Unknown Browser";
//     };

//     useEffect(() => {
//         if (!window.JitsiMeetExternalAPI) {
//             alert("JitsiMeetExternalAPI not loaded");
//             return;
//         }

//         if (!roomName || !displayName) return;

//         const domain = "vpd.zrix.com";
//         const options = {
//             roomName,
//             parentNode: containerRef.current,
//             userInfo: { displayName },
//             configOverwrite: {
//                 enableClosePage: false,
//                 openBridgeChannel: true,
//             },
//         };

//         apiRef.current = new window.JitsiMeetExternalAPI(domain, options);

//         apiRef.current.addEventListener("readyToClose", () => {
//             console.log("Meeting ended, redirecting to home");
//             navigate("/");
//         });

//         apiRef.current.addEventListener("participantJoined", (participant) => {
//             console.log("Participant joined:", participant);
//         });

//         apiRef.current.addEventListener("incomingMessage", (msg) => {
//             console.log("💬 Chat message:", msg);
//         });

//         apiRef.current.addEventListener("videoConferenceJoined", async () => {
//             // Wait briefly to ensure bridge is ready
//             console.log("Conference joined, sending user info...");
//             setTimeout(async () => {
//                 const userAgent = navigator.userAgent;
//                 const location = await getLocation();
//                 const browserInfo = parseBrowser(userAgent);

//                 const myInfo = {
//                     browser: browserInfo,
//                     location: location || "Unknown",
//                 };

//                 console.log("✅ Info sent:", myInfo);

//                 try {
//                     apiRef.current.executeCommand("sendEndpointTextMessage", "", {
//                         type: "userInfo",
//                         data: myInfo,
//                     });
//                 } catch (err) {
//                     console.error("❌ Failed to send user info:", err);
//                 }
//             }, 1000); // 1 second delay
//         });

//         apiRef.current.addEventListener("endpointTextMessageReceived", (event) => {
//             const { senderInfo, data } = event;
//             if (data.type === "userInfo") {
//                 const participantId = senderInfo?.id;
//                 const info = data.data;

//                 apiRef.current.executeCommand(
//                     "addParticipantProperty",
//                     participantId,
//                     "device_info",
//                     `${info.browser} | ${info.location}`
//                 );
//             }
//         });

//         return () => {
//             if (apiRef.current) apiRef.current.dispose();
//         };
//     }, [roomName, displayName, navigate]);

//     return <div ref={containerRef} style={{ height: "100vh", width: "100%" }} />;
// };

// export default JitsiMeeting;
// import React, { useEffect, useRef, useState } from "react";
// import { useNavigate } from "react-router-dom";
// import "./CustomChat.css";

// const JitsiMeeting = ({ roomName, displayName }) => {
//   const jitsiNode = useRef(null);
//   const apiRef = useRef(null);
//   const navigate = useNavigate();
//   const [messages, setMessages] = useState([]);
//   const [text, setText] = useState("");
//   const fileInputRef = useRef(null);

//   useEffect(() => {
//     if (!window.JitsiMeetExternalAPI) {
//       return alert("JitsiMeetExternalAPI not loaded");
//     }
//     if (!roomName || !displayName) return;

//     const options = {
//       roomName,
//       parentNode: jitsiNode.current,
//       userInfo: { displayName },
//       configOverwrite: { enableClosePage: false, openBridgeChannel: "websocket" },
//       interfaceConfigOverwrite: { DISABLE_CHAT: true }
//     };
//     const api = new window.JitsiMeetExternalAPI("vpd.zrix.com", options);
//     apiRef.current = api;

//     api.addEventListener("readyToClose", () => navigate("/"));

//     api.addEventListener("participantEndpointMessageReceived", ({ eventData }) => {
//       if (eventData?.type === "custom-chat") {
//         setMessages((m) => [...m, { ...eventData.payload, remote: true }]);
//       }
//     });

//     return () => api.dispose();
//   }, [roomName, displayName, navigate]);

//   const sendMessage = (payload) => {
//     apiRef.current.executeCommand("sendEndpointTextMessage", "", {
//       type: "custom-chat",
//       payload
//     });
//     setMessages((m) => [...m, { ...payload, remote: false }]);
//   };

//   const handleSendText = () => {
//     if (!text) return;
//     sendMessage({ text, image: null, ts: Date.now() });
//     setText("");
//   };

//   const handleFile = (e) => {
//     const file = e.target.files?.[0];
//     if (!file) return;
//     const reader = new FileReader();
//     reader.onload = () => sendMessage({ text: null, image: reader.result, ts: Date.now() });
//     reader.readAsDataURL(file);
//   };

//   return (
//     <div className="meet-wrapper">
//       <div ref={jitsiNode} className="jitsi-frame" />
//       <div className="custom-chat">
//         <div className="chat-header">Chat</div>
//         <div className="chat-body">
//           {messages.map((m, idx) => (
//             <div
//               key={idx}
//               className={`message ${m.remote ? "remote" : "local"}`}
//             >
//               {m.text && <span>{m.text}</span>}
//               {m.image && <img src={m.image} alt="chat" />}
//             </div>
//           ))}
//         </div>
//         <div className="chat-input">
//           <input
//             type="text"
//             placeholder="Type message..."
//             value={text}
//             onChange={(e) => setText(e.target.value)}
//             onKeyDown={(e) => e.key === "Enter" && handleSendText()}
//           />
//           <button onClick={() => fileInputRef.current.click()}>📷</button>
//           <input
//             type="file"
//             accept="image/*"
//             ref={fileInputRef}
//             onChange={handleFile}
//             style={{ display: "none" }}
//           />
//           <button onClick={handleSendText}>Send</button>
//         </div>
//       </div>
//     </div>
//   );
// };

// export default JitsiMeeting; Earlier working version of JitsiMeeting.jsx
// import { useEffect, useRef, useState } from "react";
// import { useNavigate } from "react-router-dom";
// const JitsiMeeting = ({ roomName, displayName }) => {
//     const containerRef = useRef(null);
//     const apiRef = useRef(null);
//     const navigate = useNavigate();
//     const [chatMessages, setChatMessages] = useState([]);
//     const [message, setMessage] = useState("");

//     useEffect(() => {
//         if (!window.JitsiMeetExternalAPI) {
//             alert("JitsiMeetExternalAPI not loaded");
//             return;
//         }

//         if (!roomName) return;

//         const domain = "vpd.zrix.com";
//         const options = {
//             roomName,
//             parentNode: containerRef.current,
//             userInfo: { displayName },
//             configOverwrite: {
//                 enableClosePage: false,
//                 openBridgeChannel: true,
//                 customParticipantMenuButtons: [
//                     {
//                         icon: 'https://cdn-icons-png.flaticon.com/512/1159/1159784.png', // A custom icon URL
//                         id: 'take-screenshot-button',
//                         text: 'Take Screenshot'
//                     },
//                 ],
//                 startsWithvideoMuted: false,
//                 startWithAudioMuted: true,
//             },
//             interfaceConfigOverwrite: {
//                 TOOLBAR_BUTTONS: ['microphone', 'camera', 'desktop', 'fullscreen',
//                     'fodeviceselection', 'hangup', 'profile', 'chat',
//                     'etherpad', 'sharedvideo', 'settings', 'raisehand',
//                     'videoquality', 'filmstrip', 'tileview', 'stats', 'shortcuts'],
//                     SHOW_JITSI_WATERMARK: false,
//                     SHOW_WATERMARK_FOR_GUESTS: false,
//                     SHOW_PROMOTIONAL_CLOSE_PAGE: false,
//                     SHOW_CHROME_EXTENSION_BANNER: false,
//                     SHOW_DEEP_LINKING_IMAGE: false,
//                     SHOW_JITSI_WATERMARK_FOR_GUESTS: false,
//                 // customParticipantMenuButtons: customButtons
//             }
//         };

//         apiRef.current = new window.JitsiMeetExternalAPI(domain, options);

//         apiRef.current.addEventListener("readyToClose", () => {
//             setShowChat(false);
//             navigate("/create")
//         });

//         apiRef.current.addEventListener("incomingMessage", (msg) => {
//         });

//         apiRef.current.addEventListener("videoConferenceJoined", async () => {

//         });
//         apiRef.current.addEventListener('participantJoined', (participant) => {
//             console.log('Participant Joined:', participant);

//             // Delay to wait for DOM to update
//         });

//         apiRef.current.addEventListener("endpointTextMessageReceived", (event) => {
//         });

//     }, [roomName, displayName, navigate]);

//     const sendMessage = () => {
//         if (message.trim()) {
//             apiRef.current.executeCommand("sendChatMessage", message);
//             setChatMessages((prev) => [...prev, { from: displayName, text: message, type: "text" }]);
//             setMessage("");
//         }
//     };

//     return (
//         <div style={{ display: "flex", height: "100vh", width: "100vw" }}>
//             <div ref={containerRef} style={{ flex: 1, height: "100%", width: "100%" }} />
//         </div>
//     );
// };

// export default JitsiMeeting;

//New version of JitsiMeeting.jsx
// src/components/JitsiMeeting.jsx - Simplified Jitsi integration
// import { useEffect, useRef, useState } from "react";
// import { useNavigate } from "react-router-dom";

// const JitsiMeeting = ({ roomName, displayName, token, role, meetingData }) => {
//     console.log("JitsiMeeting props:", { roomName, displayName, token, role, meetingData });
//     const containerRef = useRef(null);
//     const apiRef = useRef(null);
//     const navigate = useNavigate();
//     const [isConnected, setIsConnected] = useState(false);

//     useEffect(() => {
//         if (!window.JitsiMeetExternalAPI) {
//             console.error("❌ JitsiMeetExternalAPI not loaded");
//             return;
//         }

//         if (!roomName || !token) {
//             console.error("❌ Missing roomName or token");
//             return;
//         }

//         initializeJitsi();

//         return () => {
//             if (apiRef.current) {
//                 apiRef.current.dispose();
//                 apiRef.current = null;
//             }
//         };
//     }, [roomName, displayName, token, role]);

//     const initializeJitsi = () => {
//         // Your Jitsi server domain
//         // https://ce1136198bc6.ngrok-free.app
//         const domain = process.env.REACT_APP_JITSI_DOMAIN || "vpd.zrix.com";
//         const isModerator = role === 'moderator';
//         console.log("domain:", domain, "isModerator:", isModerator);
//         const options = {
//             roomName,
//             parentNode: containerRef.current,
//             jwt: token,  // JWT token provides role-based authentication
//             userInfo: {
//                 displayName: displayName || 'Guest',
//                 email: `${(displayName || 'guest').replace(/\s+/g, '').toLowerCase()}@meeting.local`
//             },
//             configOverwrite: {
//                 // Meeting behavior settings
//                 startWithVideoMuted: false,
//                 startWithAudioMuted: !isModerator,  // Moderators join unmuted
//                 enableClosePage: false,
//                 disableDeepLinking: true,
//                 prejoinPageEnabled: false,
//                 enableWelcomePage: false,

//                 // Security settings
//                 requireDisplayName: true,
//                 enableInsecureRoomNameWarning: false,

//                 // Simple feature set
//                 enableCalendarIntegration: false,
//                 enableEmailInStats: false
//             },
//             interfaceConfigOverwrite: {
//                 // Customized toolbar based on role
//                 TOOLBAR_BUTTONS: isModerator ? [
//                     // Full toolbar for moderators
//                     'microphone', 'camera', 'desktop', 'fullscreen',
//                     'hangup', 'profile', 'chat', 'settings', 'raisehand',
//                     'videoquality', 'filmstrip', 'tileview', 'stats',
//                     'security', 'invite', 'mute-everyone'
//                 ] : [
//                     // Limited toolbar for participants
//                     'microphone', 'camera', 'desktop', 'fullscreen',
//                     'hangup', 'profile', 'chat', 'raisehand',
//                     'filmstrip', 'tileview', 'stats'
//                 ],

//                 // UI customization
//                 SHOW_JITSI_WATERMARK: false,
//                 SHOW_WATERMARK_FOR_GUESTS: false,
//                 SHOW_PROMOTIONAL_CLOSE_PAGE: false,
//                 SHOW_CHROME_EXTENSION_BANNER: false,
//                 APP_NAME: meetingData?.roomName || 'Video Meeting',
//                 DEFAULT_BACKGROUND: '#1a1a1a',
//                 DISABLE_FOCUS_INDICATOR: false
//             }
//         };

//         try {
//             console.log(`🚀 Initializing Jitsi as ${role} for room: ${roomName}`);

//             apiRef.current = new window.JitsiMeetExternalAPI(domain, options);

//             // Event listeners for meeting lifecycle
//             apiRef.current.addEventListener("videoConferenceJoined", () => {
//                 console.log('✅ Successfully joined meeting');
//                 setIsConnected(true);
//             });

//             apiRef.current.addEventListener('participantJoined', (participant) => {
//                 console.log('👥 Participant joined:', participant.displayName);
//             });

//             apiRef.current.addEventListener('participantLeft', (participant) => {
//                 console.log('👋 Participant left:', participant.displayName);
//             });

//             apiRef.current.addEventListener("videoConferenceLeft", () => {
//                 console.log('👋 Left meeting');
//                 setIsConnected(false);
//             });

//             apiRef.current.addEventListener("readyToClose", () => {
//                 setIsConnected(false);
//                 navigate("/admin/dashboard");
//             });

//         } catch (error) {
//             console.error('❌ Error initializing Jitsi:', error);
//         }
//     };

//     return (
//         <div className="jitsi-wrapper">
//             <div
//                 ref={containerRef}
//                 className="jitsi-container"
//                 style={{
//                     width: "100%",
//                     height: "100%",
//                     minHeight: "500px",
//                     background: "#000"
//                 }}
//             />

//             {/* Connection Status */}
//             <div className={`connection-indicator ${isConnected ? 'connected' : 'connecting'}`}>
//                 {isConnected ? '🟢 Connected' : '🔄 Connecting...'}
//             </div>
//         </div>
//     );
// };

// export default JitsiMeeting;

// import React, { useEffect, useMemo, useRef, useState } from "react";
// import { useNavigate } from "react-router-dom";
// import axios from "../api/axiosInstance";

// const JitsiWithCustomChat = ({
//     roomName,
//     displayName,
//     token,
//     role,
//     meetingData
// }) => {
//     const containerRef = useRef(null);
//     const apiRef = useRef(null);
//     const fileInputRef = useRef(null);
//     const navigate = useNavigate();

//     const [isConnected, setIsConnected] = useState(false);
//     const [chatOpen, setChatOpen] = useState(true);
//     const [sending, setSending] = useState(false);
//     const [uploading, setUploading] = useState(false);
//     const [input, setInput] = useState("");
//     const [messages, setMessages] = useState([]);
//     const [unread, setUnread] = useState(0);

//     const isModerator = role === "moderator";
//     const localName = useMemo(() => displayName || "Guest", [displayName]);

//     useEffect(() => {
//         if (!window.JitsiMeetExternalAPI) {
//             console.error("JitsiMeetExternalAPI not loaded");
//             return;
//         }
//         if (!roomName || !token) {
//             console.error("Missing roomName or token");
//             return;
//         }
//         initializeJitsi();

//         return () => {
//             if (apiRef.current) {
//                 try {
//                     apiRef.current.dispose();
//                 } catch { }
//                 apiRef.current = null;
//             }
//         };
//     }, [roomName, token, role]);

//     const initializeJitsi = () => {
//         const domain = process.env.REACT_APP_JITSI_DOMAIN || "vpd.zrix.com";
//         const options = {
//             roomName,
//             parentNode: containerRef.current,
//             jwt: token,
//             userInfo: {
//                 displayName: localName,
//                 email: `${localName.replace(/\s+/g, "").toLowerCase()}@meeting.local`
//             },
//             configOverwrite: {
//                 startWithVideoMuted: false,
//                 startWithAudioMuted: !isModerator,
//                 disableDeepLinking: true,
//                 prejoinPageEnabled: false,
//                 enableWelcomePage: false,
//                 enableClosePage: false
//             },
//             interfaceConfigOverwrite: {
//                 TOOLBAR_BUTTONS: isModerator
//                     ? [
//                         "microphone", "camera", "desktop", "fullscreen",
//                         "hangup", "profile", "chat", "settings", "raisehand",
//                         "videoquality", "filmstrip", "tileview", "stats",
//                         "security", "invite", "mute-everyone"
//                     ]
//                     : [
//                         "microphone", "camera", "desktop", "fullscreen",
//                         "hangup", "profile", "chat", "raisehand",
//                         "filmstrip", "tileview", "stats"
//                     ],
//                 SHOW_JITSI_WATERMARK: false,
//                 SHOW_WATERMARK_FOR_GUESTS: false,
//                 SHOW_PROMOTIONAL_CLOSE_PAGE: false,
//                 SHOW_CHROME_EXTENSION_BANNER: false,
//                 APP_NAME: meetingData?.roomName || "Video Meeting",
//                 DEFAULT_BACKGROUND: "#1a1a1a",
//                 DISABLE_FOCUS_INDICATOR: false
//             }
//         };

//         try {
//             apiRef.current = new window.JitsiMeetExternalAPI(domain, options);

//             apiRef.current.addEventListener("videoConferenceJoined", () => {
//                 setIsConnected(true);
//             });

//             apiRef.current.addEventListener("videoConferenceLeft", () => {
//                 setIsConnected(false);
//             });

//             apiRef.current.addEventListener("readyToClose", () => {
//                 navigate("/admin/dashboard");
//             });

//             apiRef.current.addEventListener("incomingMessage", (evt) => {
//                 const msg = parseMessage(evt);
//                 setMessages((prev) => [...prev, msg]);
//                 if (!chatOpen) setUnread((u) => u + 1);
//             });

//         } catch (e) {
//             console.error("Error initializing Jitsi:", e);
//         }
//     };

//     const parseMessage = (evt) => {
//         const text = evt.message || "";
//         const baseMsg = {
//             id: evt.id || `${Date.now()}-${Math.random().toString(36).slice(2)}`,
//             from: evt.nick || evt.from || "Unknown",
//             me: (evt.nick || "").trim() === localName.trim(),
//             time: evt.stamp ? new Date(evt.stamp) : new Date()
//         };

//         // Check if it's a file message with our custom format
//         if (text.startsWith('[FILE]')) {
//             try {
//                 const data = JSON.parse(text.replace('[FILE]', ''));
//                 return {
//                     ...baseMsg,
//                     type: 'file',
//                     fileData: data,
//                     text: `📎 ${data.name}`
//                 };
//             } catch (e) {
//                 return { ...baseMsg, type: 'text', text };
//             }
//         }

//         return { ...baseMsg, type: 'text', text };
//     };

//     const sendMessage = async () => {
//         const text = input.trim();
//         if (!text || !apiRef.current) return;

//         setSending(true);
//         try {
//             apiRef.current.executeCommand("sendChatMessage", text);
//             setMessages((prev) => [
//                 ...prev,
//                 {
//                     id: `${Date.now()}-me`,
//                     from: localName,
//                     me: true,
//                     type: 'text',
//                     text,
//                     time: new Date()
//                 }
//             ]);
//             setInput("");
//         } catch (error) {
//             console.error('Error sending message:', error);
//         } finally {
//             setSending(false);
//         }
//     };

//     const handleFileUpload = async (file) => {
//         if (!file || !apiRef.current) return;

//         // Validate file
//         const maxSize = 25 * 1024 * 1024; // 25MB
//         if (file.size > maxSize) {
//             alert('File too large. Maximum size is 25MB.');
//             return;
//         }

//         setUploading(true);
//         try {
//             const formData = new FormData();
//             formData.append('file', file);
//             formData.append('meetingId', roomName);
//             formData.append('senderName', localName);
//             formData.append('senderRole', role);

//             // Upload to backend
//             const response = await axios.post('/chats/upload', formData, {
//                 headers: {
//                     'Content-Type': 'multipart/form-data',
//                     //   'Authorization': `Bearer ${token}`
//                 },
//                 onUploadProgress: (progressEvent) => {
//                     const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
//                     console.log(`Upload progress: ${progress}%`);
//                 }
//             });

//             const { fileUrl, fileName, fileSize, mimeType, fileType, thumbnailUrl } = response.data;

//             // Create structured message
//             const fileMessage = {
//                 type: fileType, // 'image', 'video', 'document'
//                 name: fileName,
//                 size: fileSize,
//                 mime: mimeType,
//                 url: fileUrl,
//                 thumbnailUrl: thumbnailUrl || null,
//                 uploadedBy: localName,
//                 uploadedAt: new Date().toISOString()
//             };

//             // Send to Jitsi chat with marker
//             const chatText = `[FILE]${JSON.stringify(fileMessage)}`;
//             apiRef.current.executeCommand("sendChatMessage", chatText);

//             // Add to local messages for immediate preview
//             setMessages((prev) => [
//                 ...prev,
//                 {
//                     id: `${Date.now()}-upload`,
//                     from: localName,
//                     me: true,
//                     type: 'file',
//                     fileData: fileMessage,
//                     text: `📎 ${fileName}`,
//                     time: new Date()
//                 }
//             ]);

//         } catch (error) {
//             console.error('Upload error:', error);
//             alert('Failed to upload file. Please try again.');
//         } finally {
//             setUploading(false);
//         }
//     };

//     const openFileDialog = () => {
//         fileInputRef.current?.click();
//     };

//     const handleFileSelect = (e) => {
//         const file = e.target.files[0];
//         if (file) {
//             handleFileUpload(file);
//         }
//         e.target.value = ''; // Reset input
//     };

//     const handleKeyDown = (e) => {
//         if (e.key === "Enter" && !e.shiftKey) {
//             e.preventDefault();
//             sendMessage();
//         }
//     };

//     const toggleChat = () => {
//         setChatOpen((v) => !v);
//         if (!chatOpen && unread) setUnread(0);
//     };

//     const renderMessage = (msg) => {
//         if (msg.type === 'file' && msg.fileData) {
//             return renderFileMessage(msg);
//         }
//         return <div style={styles.msgText}>{msg.text}</div>;
//     };

//     //   const renderFileMessage = (msg) => {
//     //     const { fileData } = msg;
//     //     const { type, name, size, url, thumbnailUrl, mime } = fileData;

//     //     const formatSize = (bytes) => {
//     //       if (bytes === 0) return '0 Bytes';
//     //       const k = 1024;
//     //       const sizes = ['Bytes', 'KB', 'MB', 'GB'];
//     //       const i = Math.floor(Math.log(bytes) / Math.log(k));
//     //       return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
//     //     };

//     //     switch (type) {
//     //       case 'image':
//     //         return (
//     //           <div style={styles.fileMessage}>
//     //             <img
//     //               src={thumbnailUrl || url}
//     //               alt={name}
//     //               style={styles.imagePreview}
//     //               onClick={() => window.open(url, '_blank')}
//     //             />
//     //             <div style={styles.fileInfo}>
//     //               <div style={styles.fileName}>{name}</div>
//     //               <div style={styles.fileSize}>{formatSize(size)}</div>
//     //             </div>
//     //           </div>
//     //         );

//     //       case 'video':
//     //         return (
//     //           <div style={styles.fileMessage}>
//     //             <div style={styles.videoPreview}>
//     //               {thumbnailUrl ? (
//     //                 <img src={thumbnailUrl} alt={name} style={styles.videoThumbnail} />
//     //               ) : (
//     //                 <div style={styles.videoPlaceholder}>🎥</div>
//     //               )}
//     //               <div
//     //                 style={styles.playButton}
//     //                 onClick={() => window.open(url, '_blank')}
//     //               >
//     //                 ▶
//     //               </div>
//     //             </div>
//     //             <div style={styles.fileInfo}>
//     //               <div style={styles.fileName}>{name}</div>
//     //               <div style={styles.fileSize}>{formatSize(size)}</div>
//     //             </div>
//     //           </div>
//     //         );

//     //       default: // document/other files
//     //         return (
//     //           <div style={styles.fileMessage}>
//     //             <div style={styles.fileIcon}>
//     //               {getFileIcon(mime)}
//     //             </div>
//     //             <div style={styles.fileInfo}>
//     //               <div style={styles.fileName}>{name}</div>
//     //               <div style={styles.fileSize}>{formatSize(size)}</div>
//     //               <a
//     //                 href={url}
//     //                 target="_blank"
//     //                 rel="noopener noreferrer"
//     //                 style={styles.downloadLink}
//     //               >
//     //                 Download
//     //               </a>
//     //             </div>
//     //           </div>
//     //         );
//     //     }
//     //   };

//     //   const getFileIcon = (mime) => {
//     //     if (mime?.includes('pdf')) return '📄';
//     //     if (mime?.includes('word') || mime?.includes('document')) return '📝';
//     //     if (mime?.includes('sheet') || mime?.includes('excel')) return '📊';
//     //     if (mime?.includes('presentation') || mime?.includes('powerpoint')) return '📽️';
//     //     if (mime?.includes('zip') || mime?.includes('rar')) return '📦';
//     //     if (mime?.includes('audio')) return '🎵';
//     //     return '📎';
//     //   };
//     const renderFileMessage = (msg) => {
//         const { fileData } = msg;
//         const { type, name, size, url, thumbnailUrl, mime } = fileData;

//         const formatSize = (bytes) => {
//             if (bytes === 0) return '0 Bytes';
//             const k = 1024;
//             const sizes = ['Bytes', 'KB', 'MB', 'GB'];
//             const i = Math.floor(Math.log(bytes) / Math.log(k));
//             return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
//         };

//         switch (type) {
//             case 'image':
//                 return (
//                     <div style={styles.fileMessage}>
//                         <div style={styles.imageContainer}>
//                             <img
//                                 src={thumbnailUrl || url}
//                                 alt={name}
//                                 style={styles.imagePreview}
//                                 onClick={() => window.open(url, '_blank')}
//                                 onError={(e) => {
//                                     e.target.style.display = 'none';
//                                     e.target.nextSibling.style.display = 'flex';
//                                 }}
//                             />
//                             {/* Fallback if image fails to load */}
//                             <div style={{ ...styles.imageError, display: 'none' }}>
//                                 <span>🖼️</span>
//                                 <small>Image unavailable</small>
//                             </div>
//                         </div>
//                         <div style={styles.imageOverlay}>
//                             <div style={styles.fileName}>{name}</div>
//                             <div style={styles.fileSize}>{formatSize(size)}</div>
//                         </div>
//                     </div>
//                 );

//             case 'video':
//                 return (
//                     <div style={styles.fileMessage}>
//                         <div style={styles.videoContainer}>
//                             <div style={styles.videoPreview}>
//                                 {thumbnailUrl ? (
//                                     <img
//                                         src={thumbnailUrl}
//                                         alt={name}
//                                         style={styles.videoThumbnail}
//                                         onError={(e) => {
//                                             e.target.style.display = 'none';
//                                             e.target.parentNode.querySelector('.video-placeholder').style.display = 'flex';
//                                         }}
//                                     />
//                                 ) : (
//                                     <div style={styles.videoPlaceholder} className="video-placeholder">🎥</div>
//                                 )}

//                                 {/* Hidden placeholder for fallback */}
//                                 <div style={{ ...styles.videoPlaceholder, display: 'none' }} className="video-placeholder">
//                                     🎥
//                                 </div>

//                                 <div
//                                     style={styles.playButton}
//                                     onClick={() => window.open(url, '_blank')}
//                                     title="Click to play video"
//                                 >
//                                     <div style={styles.playIcon}>▶️</div>
//                                 </div>

//                                 <div style={styles.videoDuration}>
//                                     📹 Video
//                                 </div>
//                             </div>
//                             <div style={styles.videoInfo}>
//                                 <div style={styles.fileName}>{name}</div>
//                                 <div style={styles.fileSize}>{formatSize(size)}</div>
//                             </div>
//                         </div>
//                     </div>
//                 );

//             default: // document/other files
//                 return (
//                     <div style={styles.fileMessage}>
//                         <div style={styles.documentContainer}>
//                             <div style={styles.fileIconContainer}>
//                                 <div style={styles.fileIcon}>
//                                     {getFileIcon(mime)}
//                                 </div>
//                             </div>
//                             <div style={styles.fileInfo}>
//                                 <div style={styles.fileName}>{name}</div>
//                                 <div style={styles.fileDetails}>
//                                     <span style={styles.fileSize}>{formatSize(size)}</span>
//                                     <span style={styles.fileType}>{getFileTypeName(mime)}</span>
//                                 </div>
//                                 <div style={styles.fileActions}>
//                                     <a
//                                         href={url}
//                                         target="_blank"
//                                         rel="noopener noreferrer"
//                                         style={styles.downloadBtn}
//                                         onClick={(e) => e.stopPropagation()}
//                                     >
//                                         📥 Download
//                                     </a>
//                                     <button
//                                         style={styles.viewBtn}
//                                         onClick={() => window.open(url, '_blank')}
//                                     >
//                                         👁️ View
//                                     </button>
//                                 </div>
//                             </div>
//                         </div>
//                     </div>
//                 );
//         }
//     };

//     // Enhanced helper functions
//     const getFileIcon = (mime) => {
//         if (mime?.includes('pdf')) return '📄';
//         if (mime?.includes('word') || mime?.includes('document')) return '📝';
//         if (mime?.includes('sheet') || mime?.includes('excel')) return '📊';
//         if (mime?.includes('presentation') || mime?.includes('powerpoint')) return '📽️';
//         if (mime?.includes('zip') || mime?.includes('rar') || mime?.includes('7z')) return '📦';
//         if (mime?.includes('audio')) return '🎵';
//         if (mime?.includes('text')) return '📄';
//         if (mime?.includes('csv')) return '📊';
//         return '📎';
//     };

//     const getFileTypeName = (mime) => {
//         if (mime?.includes('pdf')) return 'PDF';
//         if (mime?.includes('word')) return 'Word';
//         if (mime?.includes('document')) return 'Document';
//         if (mime?.includes('sheet') || mime?.includes('excel')) return 'Spreadsheet';
//         if (mime?.includes('presentation') || mime?.includes('powerpoint')) return 'Presentation';
//         if (mime?.includes('zip')) return 'ZIP Archive';
//         if (mime?.includes('rar')) return 'RAR Archive';
//         if (mime?.includes('7z')) return '7Z Archive';
//         if (mime?.includes('text')) return 'Text';
//         if (mime?.includes('csv')) return 'CSV';
//         return 'File';
//     };

//     return (
//         <div style={styles.shell}>
//             <div style={styles.meetingPane}>
//                 <div ref={containerRef} style={styles.jitsiContainer} />

//                 {!isConnected && (
//                     <div style={styles.connectingBanner}>
//                         <span>🔄 Connecting to meeting...</span>
//                     </div>
//                 )}

//                 <button
//                     onClick={toggleChat}
//                     style={styles.fab}
//                     title="Toggle custom chat"
//                 >
//                     💬
//                     {unread > 0 && <span style={styles.badge}>{unread}</span>}
//                 </button>
//             </div>

//             <aside
//                 style={{
//                     ...styles.chatPane,
//                     transform: chatOpen ? "translateX(0)" : "translateX(400px)"
//                 }}
//             >
//                 <header style={styles.chatHeader}>
//                     <div style={styles.chatHeaderLeft}>
//                         <span style={styles.chatTitle}>Chat</span>
//                         <small style={styles.chatSub}>
//                             {meetingData?.roomName || roomName}
//                         </small>
//                     </div>
//                     <button
//                         onClick={toggleChat}
//                         style={styles.chatCloseBtn}
//                         title="Close chat"
//                     >
//                         ✕
//                     </button>
//                 </header>

//                 <div style={styles.chatBody}>
//                     {messages.length === 0 ? (
//                         <div style={styles.emptyState}>
//                             <div style={styles.emptyIcon}>💬</div>
//                             <div>No messages yet</div>
//                             <small>Send messages and share files with everyone</small>
//                         </div>
//                     ) : (
//                         messages.map((m) => (
//                             <div
//                                 key={m.id}
//                                 style={{
//                                     ...styles.msgRow,
//                                     justifyContent: m.me ? "flex-end" : "flex-start"
//                                 }}
//                             >
//                                 <div
//                                     style={{
//                                         ...styles.msgBubble,
//                                         background: m.me ? "#2b62d9" : "#2a2a2a",
//                                         minWidth: m.type === 'file' ? '250px' : 'auto',
//                                         // Special styling for file messages
//                                         ...(m.type === 'file' && {
//                                             background: 'transparent',
//                                             padding: '4px',
//                                             boxShadow: 'none'
//                                         })
//                                     }}
//                                 >
//                                     <div style={styles.msgMeta}>
//                                         <span style={styles.msgSender}>
//                                             {m.me ? "Me" : m.from}
//                                         </span>
//                                         <span style={styles.msgTime}>
//                                             {new Intl.DateTimeFormat(undefined, {
//                                                 hour: "2-digit",
//                                                 minute: "2-digit"
//                                             }).format(m.time)}
//                                         </span>
//                                     </div>
//                                     {renderMessage(m)}
//                                 </div>
//                             </div>
//                         ))
//                     )}
//                 </div>

//                 <footer style={styles.chatFooter}>
//                     <div style={styles.inputRow}>
//                         <textarea
//                             placeholder="Type a message…"
//                             value={input}
//                             onChange={(e) => setInput(e.target.value)}
//                             onKeyDown={handleKeyDown}
//                             style={styles.input}
//                             rows={1}
//                         />
//                         <button
//                             onClick={openFileDialog}
//                             disabled={uploading}
//                             style={styles.attachBtn}
//                             title="Upload file, image, or video"
//                         >
//                             {uploading ? "⏳" : "📎"}
//                         </button>
//                     </div>
//                     <button
//                         onClick={sendMessage}
//                         disabled={!input.trim() || sending}
//                         style={{
//                             ...styles.sendBtn,
//                             opacity: (!input.trim() || sending) ? 0.5 : 1,
//                             cursor: (!input.trim() || sending) ? 'not-allowed' : 'pointer'
//                         }}
//                     >
//                         {sending ? "..." : "Send"}
//                     </button>
//                 </footer>

//                 <input
//                     ref={fileInputRef}
//                     type="file"
//                     style={{ display: 'none' }}
//                     onChange={handleFileSelect}
//                     accept="image/*,video/*,.pdf,.doc,.docx,.txt,.zip,.rar"
//                     multiple={false}
//                 />
//             </aside>
//         </div>
//     );
// };

// // Enhanced Styles
// const styles = {
//     shell: {
//         display: "grid",
//         gridTemplateColumns: "1fr auto",
//         height: "100vh",
//         background: "#101014",
//         color: "#e8e8ea",
//         overflow: "hidden",
//         fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
//     },
//     meetingPane: {
//         position: "relative",
//         height: "100%",
//         overflow: "hidden"
//     },
//     jitsiContainer: {
//         width: "100%",
//         height: "100%",
//         minHeight: 500,
//         background: "#000"
//     },
//     connectingBanner: {
//         position: "absolute",
//         top: 12,
//         left: 12,
//         background: "rgba(0,0,0,0.8)",
//         border: "1px solid rgba(255,255,255,0.1)",
//         borderRadius: 8,
//         padding: "8px 12px",
//         fontSize: 12,
//         color: "#fff",
//         backdropFilter: "blur(8px)"
//     },
//     fab: {
//         position: "absolute",
//         right: 16,
//         bottom: 16,
//         background: "linear-gradient(135deg, #2b62d9, #1e4ba8)",
//         color: "#fff",
//         border: "none",
//         borderRadius: "50%",
//         width: 56,
//         height: 56,
//         fontSize: 20,
//         cursor: "pointer",
//         boxShadow: "0 8px 24px rgba(43, 98, 217, 0.4)",
//         display: "flex",
//         alignItems: "center",
//         justifyContent: "center",
//         position: "relative"
//     },
//     badge: {
//         position: "absolute",
//         top: -4,
//         right: -4,
//         background: "#e5484d",
//         color: "#fff",
//         fontSize: 10,
//         fontWeight: "bold",
//         borderRadius: "50%",
//         minWidth: 18,
//         height: 18,
//         display: "flex",
//         alignItems: "center",
//         justifyContent: "center",
//         border: "2px solid #101014"
//     },
//     chatPane: {
//         width: 400,
//         background: "#15161a",
//         borderLeft: "1px solid rgba(255,255,255,0.08)",
//         height: "100%",
//         display: "grid",
//         gridTemplateRows: "auto 1fr auto",
//         transition: "transform 250ms cubic-bezier(0.4, 0, 0.2, 1)"
//     },
//     chatHeader: {
//         padding: "16px 18px",
//         display: "flex",
//         alignItems: "center",
//         justifyContent: "space-between",
//         borderBottom: "1px solid rgba(255,255,255,0.08)",
//         background: "linear-gradient(135deg, #111216, #0f1014)"
//     },
//     chatHeaderLeft: {
//         display: "flex",
//         flexDirection: "column",
//         gap: 2
//     },
//     chatTitle: {
//         fontWeight: 700,
//         fontSize: 15,
//         color: "#fff"
//     },
//     chatSub: {
//         opacity: 0.6,
//         fontSize: 11,
//         color: "#a1a1a1"
//     },
//     chatCloseBtn: {
//         background: "transparent",
//         color: "#e8e8ea",
//         border: "1px solid rgba(255,255,255,0.15)",
//         borderRadius: 6,
//         padding: "6px 10px",
//         cursor: "pointer",
//         fontSize: 12
//     },
//     chatBody: {
//         overflowY: "auto",
//         padding: 16,
//         display: "flex",
//         flexDirection: "column",
//         gap: 12
//     },
//     emptyState: {
//         margin: "auto",
//         textAlign: "center",
//         opacity: 0.7,
//         display: "flex",
//         flexDirection: "column",
//         alignItems: "center",
//         gap: 8,
//         padding: 20
//     },
//     emptyIcon: {
//         fontSize: 32,
//         marginBottom: 8
//     },
//     msgRow: {
//         display: "flex",
//         marginBottom: 4
//     },
//     msgBubble: {
//         maxWidth: "85%",
//         borderRadius: 16,
//         padding: "10px 14px",
//         boxShadow: "0 2px 8px rgba(0,0,0,0.3)",
//         wordBreak: "break-word"
//     },
//     msgMeta: {
//         display: "flex",
//         justifyContent: "space-between",
//         alignItems: "center",
//         gap: 8,
//         fontSize: 10,
//         opacity: 0.8,
//         marginBottom: 6
//     },
//     msgSender: {
//         fontWeight: 600,
//         textTransform: "capitalize"
//     },
//     msgTime: {
//         fontVariantNumeric: "tabular-nums",
//         fontSize: 9
//     },
//     msgText: {
//         whiteSpace: "pre-wrap",
//         fontSize: 14,
//         lineHeight: 1.4,
//         color: "#fff"
//     },
//     chatFooter: {
//         borderTop: "1px solid rgba(255,255,255,0.08)",
//         padding: 12,
//         background: "#121318",
//         display: "flex",
//         flexDirection: "column",
//         gap: 10
//     },
//     inputRow: {
//         display: "flex",
//         gap: 8,
//         alignItems: "flex-end"
//     },
//     input: {
//         flex: 1,
//         resize: "none",
//         minHeight: 40,
//         maxHeight: 120,
//         borderRadius: 12,
//         background: "#0f1014",
//         color: "#fff",
//         border: "1px solid rgba(255,255,255,0.12)",
//         padding: "10px 14px",
//         outline: "none",
//         fontSize: 14
//     },
//     attachBtn: {
//         background: "#374151",
//         color: "#fff",
//         border: "none",
//         borderRadius: 10,
//         width: 40,
//         height: 40,
//         cursor: "pointer",
//         fontSize: 16,
//         display: "flex",
//         alignItems: "center",
//         justifyContent: "center"
//     },
//     sendBtn: {
//         background: "linear-gradient(135deg, #2b62d9, #1e4ba8)",
//         color: "#fff",
//         border: "none",
//         borderRadius: 12,
//         padding: "10px 20px",
//         fontWeight: 600,
//         fontSize: 14,
//         cursor: "pointer",
//         height: 40
//     },

//     // File message styles
//    fileMessage: {
//     display: "flex",
//     flexDirection: "column",
//     gap: 0,
//     padding: 0,
//     background: "transparent",
//     borderRadius: 12,
//     overflow: "hidden",
//     marginTop: 4,
//     maxWidth: "280px"
//   },

//   // Image styles
//   imageContainer: {
//     position: "relative",
//     borderRadius: 12,
//     overflow: "hidden",
//     background: "#1a1a1a"
//   },
//   imagePreview: {
//     width: "100%",
//     maxWidth: 280,
//     height: "auto",
//     maxHeight: 300,
//     borderRadius: 12,
//     cursor: "pointer",
//     objectFit: "cover",
//     transition: "transform 0.2s ease"
//   },
//   imageError: {
//     width: "100%",
//     height: 150,
//     display: "flex",
//     flexDirection: "column",
//     alignItems: "center",
//     justifyContent: "center",
//     background: "#2a2a2a",
//     borderRadius: 12,
//     color: "#888",
//     fontSize: 12
//   },
//   imageOverlay: {
//     position: "absolute",
//     bottom: 0,
//     left: 0,
//     right: 0,
//     background: "linear-gradient(transparent, rgba(0,0,0,0.7))",
//     padding: "20px 12px 8px",
//     color: "white"
//   },

//   // Video styles
//   videoContainer: {
//     borderRadius: 12,
//     overflow: "hidden",
//     background: "#1a1a1a"
//   },
//   videoPreview: {
//     position: "relative",
//     width: "100%",
//     height: 180,
//     borderRadius: 12,
//     overflow: "hidden",
//     background: "#000"
//   },
//   videoThumbnail: {
//     width: "100%",
//     height: "100%",
//     objectFit: "cover"
//   },
//   videoPlaceholder: {
//     width: "100%",
//     height: "100%",
//     background: "linear-gradient(135deg, #333, #555)",
//     display: "flex",
//     alignItems: "center",
//     justifyContent: "center",
//     fontSize: 32,
//     color: "#888"
//   },
//   playButton: {
//     position: "absolute",
//     top: "50%",
//     left: "50%",
//     transform: "translate(-50%, -50%)",
//     background: "rgba(0,0,0,0.8)",
//     borderRadius: "50%",
//     width: 56,
//     height: 56,
//     display: "flex",
//     alignItems: "center",
//     justifyContent: "center",
//     cursor: "pointer",
//     transition: "all 0.3s ease",
//     border: "3px solid rgba(255,255,255,0.9)"
//   },
//   playIcon: {
//     fontSize: 18,
//     marginLeft: 2
//   },
//   videoDuration: {
//     position: "absolute",
//     bottom: 8,
//     right: 8,
//     background: "rgba(0,0,0,0.7)",
//     color: "white",
//     padding: "2px 6px",
//     borderRadius: 4,
//     fontSize: 10,
//     fontWeight: 600
//   },
//   videoInfo: {
//     padding: "8px 12px",
//     background: "rgba(255,255,255,0.05)"
//   },

//   // Document styles
//   documentContainer: {
//     display: "flex",
//     gap: 12,
//     alignItems: "flex-start",
//     padding: 12,
//     background: "rgba(255,255,255,0.05)",
//     borderRadius: 12,
//     border: "1px solid rgba(255,255,255,0.1)"
//   },
//   fileIconContainer: {
//     background: "rgba(43, 98, 217, 0.2)",
//     borderRadius: 8,
//     padding: 8,
//     minWidth: 48,
//     height: 48,
//     display: "flex",
//     alignItems: "center",
//     justifyContent: "center"
//   },
//   fileIcon: {
//     fontSize: 24
//   },
//   fileInfo: {
//     flex: 1,
//     display: "flex",
//     flexDirection: "column",
//     gap: 4,
//     minWidth: 0
//   },
//   fileName: {
//     fontWeight: 600,
//     fontSize: 13,
//     color: "#fff",
//     wordBreak: "break-word",
//     lineHeight: 1.3
//   },
//   fileDetails: {
//     display: "flex",
//     gap: 8,
//     alignItems: "center",
//     flexWrap: "wrap"
//   },
//   fileSize: {
//     fontSize: 11,
//     color: "#999"
//   },
//   fileType: {
//     fontSize: 10,
//     color: "#2b62d9",
//     background: "rgba(43, 98, 217, 0.2)",
//     padding: "2px 6px",
//     borderRadius: 4,
//     fontWeight: 500,
//     textTransform: "uppercase"
//   },
//   fileActions: {
//     display: "flex",
//     gap: 8,
//     marginTop: 4
//   },
//   downloadBtn: {
//     color: "#2b62d9",
//     textDecoration: "none",
//     fontSize: 11,
//     fontWeight: 600,
//     padding: "4px 8px",
//     background: "rgba(43, 98, 217, 0.1)",
//     borderRadius: 6,
//     transition: "background 0.2s ease"
//   },
//   viewBtn: {
//     color: "#888",
//     background: "rgba(255,255,255,0.1)",
//     border: "none",
//     fontSize: 11,
//     fontWeight: 600,
//     padding: "4px 8px",
//     borderRadius: 6,
//     cursor: "pointer",
//     transition: "background 0.2s ease"
//   },

//   // Enhanced message bubble for files
//   msgBubble: {
//     maxWidth: "85%",
//     borderRadius: 16,
//     padding: "10px 14px",
//     boxShadow: "0 2px 8px rgba(0,0,0,0.3)",
//     wordBreak: "break-word",
//     // Special handling for file messages
//     '&.file-message': {
//       padding: "8px",
//       background: "transparent"
//     }
//   }
// };

// export default JitsiWithCustomChat;

import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useNavigate } from "react-router-dom";
import axios from "../config/axiosInstance";
import Lightbox from "../components/Lightbox";

const JitsiWithCustomChat = ({
  roomName,
  displayName,
  token,
  role,
  meetingData,
}) => {
  const containerRef = useRef(null);
  const apiRef = useRef(null);
  const fileInputRef = useRef(null);
  const chatBodyRef = useRef(null);
  const navigate = useNavigate();

  const [isConnected, setIsConnected] = useState(false);
  const [chatOpen, setChatOpen] = useState(true);
  const [sending, setSending] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [input, setInput] = useState("");
  const [messages, setMessages] = useState([]);
  const [unread, setUnread] = useState(0);

  const isModerator = role === "moderator";
  const localName = useMemo(() => displayName || "Guest", [displayName]);

  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [lightboxMedia, setLightboxMedia] = useState({
    url: null,
    type: null,
    fileName: null,
    thumbnailUrl: null,
  });

  // Auto-scroll to bottom when new messages arrive
  //   useEffect(() => {
  //     if (chatBodyRef.current) {
  //       chatBodyRef.current.scrollTop = chatBodyRef.current.scrollHeight;
  //     }
  //   }, [messages]);
  const scrollToBottom = useCallback(() => {
    if (chatBodyRef.current) {
      const scrollElement = chatBodyRef.current;
      scrollElement.scrollTo({
        top: scrollElement.scrollHeight,
        behavior: "smooth",
      });
    }
  }, []);

  // Auto-scroll when new messages arrive
  useEffect(() => {
    const timer = setTimeout(() => {
      scrollToBottom();
    }, 100); // Small delay to ensure DOM updates

    return () => clearTimeout(timer);
  }, [messages, scrollToBottom]);

  // Scroll to bottom when chat opens
  useEffect(() => {
    if (chatOpen) {
      setTimeout(() => {
        scrollToBottom();
      }, 300); // Wait for animation to complete
    }
  }, [chatOpen, scrollToBottom]);

  useEffect(() => {
    if (!window.JitsiMeetExternalAPI) {
      console.error("JitsiMeetExternalAPI not loaded");
      return;
    }
    if (!roomName || !token) {
      console.error("Missing roomName or token");
      return;
    }
    initializeJitsi();

    return () => {
      if (apiRef.current) {
        try {
          apiRef.current.dispose();
        } catch {}
        apiRef.current = null;
      }
    };
  }, [roomName, token, role]);

  const initializeJitsi = () => {
    const domain = process.env.REACT_APP_JITSI_DOMAIN || "vpd.zrix.com";
    const options = {
      roomName,
      parentNode: containerRef.current,
      jwt: token,
      userInfo: {
        displayName: localName,
        email: `${localName.replace(/\s+/g, "").toLowerCase()}@meeting.local`,
      },
      configOverwrite: {
        startWithVideoMuted: false,
        startWithAudioMuted: !isModerator,
        disableDeepLinking: true,
        prejoinPageEnabled: false,
        enableWelcomePage: false,
        enableClosePage: false,
        disabledNotifications: [
          "notify.chatMessages", // Disables notifications when receiving chat messages while chat window is closed
        ],
      },
      interfaceConfigOverwrite: {
        TOOLBAR_BUTTONS: isModerator
          ? [
              "microphone",
              "camera",
              "desktop",
              "fullscreen",
              "hangup",
              "profile",
              "settings",
              "raisehand",
              "videoquality",
              "filmstrip",
              "tileview",
              "stats",
              "security",
              "invite",
              "mute-everyone",
            ]
          : [
              "microphone",
              "camera",
              "desktop",
              "fullscreen",
              "hangup",
              "profile",
              "raisehand",
              "filmstrip",
              "stats",
            ],
        SHOW_JITSI_WATERMARK: false,
        SHOW_WATERMARK_FOR_GUESTS: false,
        SHOW_PROMOTIONAL_CLOSE_PAGE: false,
        SHOW_CHROME_EXTENSION_BANNER: false,
        APP_NAME: meetingData?.roomName || "Video Meeting",
        DEFAULT_BACKGROUND: "#1a1a1a",
        DISABLE_FOCUS_INDICATOR: true,
        DISABLE_DOMINANT_SPEAKER_INDICATOR: true,
        TILE_VIEW_MAX_COLUMNS: 2,
      },
    };

    try {
      apiRef.current = new window.JitsiMeetExternalAPI(domain, options);

      apiRef.current.addEventListener("videoConferenceJoined", () => {
        // console.log("✅ Joined meeting successfully");
        // setIsConnected(true);
        // // Load chat history when joined
        // loadChatHistory();
        apiRef.current.executeCommand("toggleTileView");

        console.log("✅ Joined meeting successfully");
        setIsConnected(true);

        // Clear messages first to prevent mixing with Jitsi's internal history
        setMessages([]);

        // Load chat history after a small delay to avoid race conditions
        setTimeout(() => {
          loadChatHistory();
        }, 1500);
      });

      apiRef.current.addEventListener("tileViewChanged", (evt) => {
        console.log("Tile view changed:", evt);
        if (!evt.enabled) {
          setTimeout(() => {
            apiRef.current.executeCommand("toggleTileView");
          }, 500);
        }
      });

      apiRef.current.addEventListener("videoConferenceLeft", () => {
        setIsConnected(false);
      });

      apiRef.current.addEventListener("readyToClose", () => {
        navigate("/admin/dashboard");
      });

      apiRef.current.addEventListener("incomingMessage", (evt) => {
        console.log("📥 Incoming message:", evt);
        const msg = parseMessage(evt);
        console.log("Parsed message:", msg);

        setMessages((prev) => {
          const isDuplicate = prev.some((existingMsg) => {
            console.log("Checking message existence:", {
              existingMsg: {
                id: existingMsg.id,
                from: existingMsg.from,
                text: existingMsg.text,
                messageHash: existingMsg.messageHash,
                jitsiFrom: existingMsg.jitsiFrom,
                source: existingMsg.source,
              },
              newMsg: {
                id: msg.id,
                from: msg.from,
                text: msg.text,
                messageHash: msg.messageHash,
                jitsiFrom: msg.jitsiFrom,
                source: msg.source,
              },
            });

            // Priority 1: Exact hash match (most reliable)
            if (existingMsg.messageHash === msg.messageHash) {
              console.log("🔍 Duplicate found: Hash match");
              return true;
            }

            // Priority 2: Same sender + same text + time window
            const timeDiff = Math.abs(
              new Date(existingMsg.time).getTime() -
                new Date(msg.time).getTime()
            );
            if (
              existingMsg.from === msg.from &&
              existingMsg.text === msg.text &&
              timeDiff < 15000
            ) {
              // 15 second window
              console.log("🔍 Duplicate found: Content + time match");
              return true;
            }

            // Priority 3: MongoDB ID match (exact database record)
            if (existingMsg.id === msg.id && msg.id.length > 10) {
              console.log("🔍 Duplicate found: Database ID match");
              return true;
            }

            return false;
          });

          if (isDuplicate) {
            console.log("❌ Skipping duplicate message");
            return prev;
          }

          console.log("✅ Adding new message from Jitsi event");
          return [...prev, msg];
        });
        if (!chatOpen) setUnread((u) => u + 1);
      });
    } catch (e) {
      console.error("Error initializing Jitsi:", e);
    }
  };

  // Load chat history from backend
  // const loadChatHistory = async () => {
  //     try {
  //         const response = await axios.get(`/chats/messages/${roomName}`, {
  //             // headers: {
  //             //     'Authorization': `Bearer ${token}`
  //             // }
  //         });
  //         console.log("📜 Chat history response:", response.data.messages);

  //         if (response.data.success) {
  //             // const historyMessages = response.data.messages.map(msg => ({
  //             //     id: msg.id,
  //             //     from: msg.senderName,
  //             //     me: msg.from === localName,
  //             //     type: msg.type,
  //             //     text: msg.text,
  //             //     fileData: msg.fileData,
  //             //     time: new Date(msg.time)
  //             // }));
  //             // setMessages(prev => [...historyMessages, ...prev]);
  //             const historyMessages = response.data.messages.map(msg => ({
  //                 id: msg.id,
  //                 from: msg.from,
  //                 me: msg.from === localName,
  //                 type: msg.type,
  //                 text: msg.text,
  //                 fileData: msg.fileData,
  //                 time: new Date(msg.time),
  //                 jitsiMessageId: msg.jitsiMessageId,
  //                 messageHash: msg.messageHash,
  //                 jitsiFrom: msg.jitsiFrom,
  //                 jitsiTimestamp: msg.jitsiTimestamp,
  //             }));
  //             setMessages(historyMessages);
  //         }
  //     } catch (error) {
  //         console.error("Failed to load chat history:", error);
  //     }
  // };
  const loadChatHistory = async () => {
    try {
      console.log("📚 Loading chat history from backend...");

      const response = await axios.get(`/chats/messages/${roomName}`, {
        headers: { Authorization: `Bearer ${token}` },
      });

      if (response.data.success) {
        const historyMessages = response.data.messages.map((msg) => {
          // Ensure consistent messageHash format
          const normalizedHash =
            msg.messageHash ||
            `${msg.from}-${msg.text
              .substring(0, 100)
              .replace(/\s+/g, " ")
              .trim()}-${Math.floor(new Date(msg.time).getTime() / 30000)}`;

          return {
            id: msg.id,
            from: msg.from,
            me: msg.from === localName,
            type: msg.type,
            text: msg.text,
            fileData: msg.fileData,
            time: new Date(msg.time),
            messageHash: normalizedHash,
            jitsiFrom: msg.jitsiFrom || "backend",
            jitsiTimestamp: new Date(msg.time).getTime(),
            source: "backend_api",
          };
        });

        console.log(
          `📚 Loaded ${historyMessages.length} messages from backend`
        );

        // Sort messages by time to maintain chronological order
        historyMessages.sort((a, b) => new Date(a.time) - new Date(b.time));

        setMessages(historyMessages);
      }
    } catch (error) {
      console.error("❌ Failed to load chat history:", error);
    }
  };

  // const parseMessage = (evt) => {
  //     const text = evt.message || "";
  //     const baseMsg = {
  //         id: evt.id || `${Date.now()}-${Math.random().toString(36).slice(2)}`,
  //         from: evt.nick || evt.from || "Unknown",
  //         me: (evt.nick || "").trim() === localName.trim(),
  //         time: evt.stamp ? new Date(evt.stamp) : new Date()
  //     };
  const parseMessage = (evt) => {
    const text = evt.message || "";
    const sender = evt.nick || evt.from || "Unknown";
    const timestamp = evt.stamp ? new Date(evt.stamp).getTime() : Date.now();

    // Normalize timestamp to 30-second windows for consistent hashing
    const normalizedTimestamp = Math.floor(timestamp / 30000);

    // Create consistent hash regardless of source
    const messageHash = `${sender}-${text
      .substring(0, 100)
      .replace(/\s+/g, " ")
      .trim()}-${normalizedTimestamp}`;

    const baseMsg = {
      id: evt.id || messageHash, // Use hash as ID for Jitsi messages
      from: sender,
      me: sender.trim() === localName.trim(),
      time: evt.stamp ? new Date(evt.stamp) : new Date(),
      messageHash,
      jitsiFrom: evt.from,
      jitsiTimestamp: timestamp,
      source: "jitsi_event",
    };

    if (text.startsWith("[FILE]")) {
      try {
        const data = JSON.parse(text.replace("[FILE]", ""));
        return {
          ...baseMsg,
          type: "file",
          fileData: data,
          text: `📎 ${data.name}`,
        };
      } catch (e) {
        return { ...baseMsg, type: "text", text };
      }
    }

    return { ...baseMsg, type: "text", text };
  };

  // const sendMessage = async () => {
  //     const text = input.trim();
  //     if (!text || !apiRef.current) return;

  //     setSending(true);
  //     try {
  //         apiRef.current.executeCommand("sendChatMessage", text);
  //         setMessages((prev) => [
  //             ...prev,
  //             {
  //                 id: `${Date.now()}-me`,
  //                 from: localName,
  //                 me: true,
  //                 type: 'text',
  //                 text,
  //                 time: new Date()
  //             }
  //         ]);
  //         setInput("");
  //     } catch (error) {
  //         console.error('Error sending message:', error);
  //     } finally {
  //         setSending(false);
  //     }
  // };
  // const sendMessage = async () => {
  //     const text = input.trim();
  //     if (!text || !apiRef.current) return;

  //     setSending(true);
  //     try {
  //         apiRef.current.executeCommand("sendChatMessage", text);
  //         setMessages((prev) => [
  //             ...prev,
  //             {
  //                 id: `${Date.now()}-me`,
  //                 from: localName,
  //                 me: true,
  //                 type: 'text',
  //                 text,
  //                 time: new Date(),
  //                 status: 'sending'
  //             }
  //         ]);
  //         setInput("");
  //         // Scroll to bottom after sending message
  //         setTimeout(scrollToBottom, 50);
  //     } catch (error) {
  //         console.error('Error sending message:', error);
  //     } finally {
  //         setSending(false);
  //     }
  // };
  // const sendMessage = async () => {
  //     const text = input.trim();
  //     if (!text || !apiRef.current) return;

  //     setSending(true);
  //     const timestamp = Date.now();
  //     const messageHash = `${localName}-${text.substring(0, 50)}-${Math.floor(timestamp / 1000)}`;
  //     const tempId = `${timestamp}-me`;

  //     try {
  //         // Send to Jitsi first
  //         apiRef.current.executeCommand("sendChatMessage", text);

  //         // Add to local messages immediately
  //         const localMessage = {
  //             id: tempId,
  //             from: localName,
  //             me: true,
  //             type: 'text',
  //             text,
  //             time: new Date(),
  //             status: 'sending',
  //             messageHash,
  //             jitsiFrom: 'self' // Mark as own message
  //         };

  //         setMessages((prev) => {
  //             // Check if we already have this message
  //             const exists = prev.find(m =>
  //                 m.messageHash === messageHash ||
  //                 (m.text === text && m.me && Math.abs(new Date(m.time).getTime() - timestamp) < 5000)
  //             );

  //             if (exists) {
  //                 console.log('Duplicate send attempt detected');
  //                 return prev;
  //             }

  //             return [...prev, localMessage];
  //         });

  //         setInput("");

  //         // Save to backend
  //         const response = await axios.post('/chats/text', {
  //             meetingId: roomName,
  //             senderName: localName,
  //             senderRole: role,
  //             textContent: text,
  //             messageHash,
  //             jitsiFrom: 'self'
  //         }, {
  //             headers: {
  //                 'Authorization': `Bearer ${token}`
  //             }
  //         });

  //         console.log('✅ Text message saved to backend:', response.data);

  //         // Update message status if not duplicate
  //         if (!response.data.duplicate) {
  //             setMessages((prev) => prev.map(msg =>
  //                 msg.id === tempId
  //                     ? {
  //                         ...msg,
  //                         status: 'sent',
  //                         id: response.data.data.id,
  //                         messageHash: response.data.data.messageHash
  //                     }
  //                     : msg
  //             ));
  //         }

  //     } catch (error) {
  //         console.error('Error sending/saving message:', error);

  //         // Update message status to failed
  //         setMessages((prev) => prev.map(msg =>
  //             msg.id === tempId
  //                 ? { ...msg, status: 'failed' }
  //                 : msg
  //         ));
  //     } finally {
  //         setSending(false);
  //     }
  // };
  const openLightbox = (mediaUrl, mediaType, fileName, thumbnailUrl = null) => {
    setLightboxMedia({
      url: mediaUrl,
      type: mediaType,
      fileName: fileName,
      thumbnailUrl: thumbnailUrl,
    });
    setLightboxOpen(true);
  };

  // Close lightbox function
  const closeLightbox = () => {
    setLightboxOpen(false);
    setLightboxMedia({
      url: null,
      type: null,
      fileName: null,
      thumbnailUrl: null,
    });
  };

  const sendMessage = async () => {
    const text = input.trim();
    if (!text || !apiRef.current) return;

    setSending(true);
    const timestamp = Date.now();
    const normalizedTimestamp = Math.floor(timestamp / 30000);
    const normalizedText = text.substring(0, 100).replace(/\s+/g, " ").trim();
    const messageHash = `${localName}-${normalizedText}-${normalizedTimestamp}`;
    const tempId = `temp-${timestamp}`;

    console.log(`📤 Sending message with hash: ${messageHash}`);

    try {
      // Check for duplicate before sending
      const existingMessage = messages.find(
        (m) => m.messageHash === messageHash
      );
      if (existingMessage) {
        console.log("🔍 Duplicate message detected, not sending");
        setSending(false);
        return;
      }

      // Send to Jitsi first
      apiRef.current.executeCommand("sendChatMessage", text);

      // Add to local messages immediately
      const localMessage = {
        id: tempId,
        from: localName,
        me: true,
        type: "text",
        text,
        time: new Date(),
        status: "sending",
        messageHash,
        jitsiFrom: "self",
        source: "local_send",
      };

      setMessages((prev) => [...prev, localMessage]);
      setInput("");

      // Save to backend
      const response = await axios.post(
        "/chats/text",
        {
          meetingId: roomName,
          senderName: localName,
          senderRole: role,
          textContent: text,
          jitsiFrom: "self",
          jitsiTimestamp: timestamp,
        },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );

      console.log("✅ Text message saved to backend:", response.data);

      // Update message with backend ID if not duplicate
      if (!response.data.duplicate) {
        setMessages((prev) =>
          prev.map((msg) =>
            msg.id === tempId
              ? {
                  ...msg,
                  status: "sent",
                  id: response.data.data.id,
                }
              : msg
          )
        );
      } else {
        // Remove local message if it was a duplicate
        setMessages((prev) => prev.filter((msg) => msg.id !== tempId));
      }
    } catch (error) {
      console.error("❌ Error sending/saving message:", error);

      setMessages((prev) =>
        prev.map((msg) =>
          msg.id === tempId ? { ...msg, status: "failed" } : msg
        )
      );
    } finally {
      setSending(false);
    }
  };

  const handleFileUpload = async (file) => {
    if (!file || !apiRef.current) return;

    // Validate file
    const maxSize = 25 * 1024 * 1024; // 25MB
    if (file.size > maxSize) {
      alert("File too large. Maximum size is 25MB.");
      return;
    }

    setUploading(true);

    // Show upload progress message immediately
    const uploadingMessage = {
      id: `uploading-${Date.now()}`,
      from: localName,
      me: true,
      type: "uploading",
      text: `📤 Uploading ${file.name}...`,
      time: new Date(),
    };
    setMessages((prev) => [...prev, uploadingMessage]);

    try {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("meetingId", roomName);
      formData.append("senderName", localName);
      formData.append("senderRole", role);

      console.log("📤 Starting file upload...");

      // Upload to backend
      const response = await axios.post("/chats/upload", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        onUploadProgress: (progressEvent) => {
          const progress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          console.log(`Upload progress: ${progress}%`);

          // Update progress message
          setMessages((prev) =>
            prev.map((msg) =>
              msg.id === uploadingMessage.id
                ? { ...msg, text: `📤 Uploading ${file.name}... ${progress}%` }
                : msg
            )
          );
        },
      });

      console.log("✅ Upload response:", response.data);

      // Remove uploading message
      setMessages((prev) =>
        prev.filter((msg) => msg.id !== uploadingMessage.id)
      );

      const responseData = response.data.data || response.data;
      const { fileUrl, fileName, fileSize, mimeType, fileType, thumbnailUrl } =
        responseData;

      console.log("📁 File data:", {
        fileUrl,
        fileName,
        fileType,
        thumbnailUrl,
      });

      // Create structured message
      const fileMessage = {
        type: fileType, // 'image', 'video', 'document'
        name: fileName,
        size: fileSize,
        mime: mimeType,
        url: fileUrl,
        thumbnailUrl: thumbnailUrl || null,
        uploadedBy: localName,
        uploadedAt: new Date().toISOString(),
      };

      // Send to Jitsi chat with marker
      const chatText = `[FILE]${JSON.stringify(fileMessage)}`;
      console.log("📨 Sending to Jitsi chat:", chatText);

      apiRef.current.executeCommand("sendChatMessage", chatText);

      // Add to local messages for immediate preview
      const newMessage = {
        id: `${Date.now()}-upload`,
        from: localName,
        me: true,
        type: "file",
        fileData: fileMessage,
        text: `📎 ${fileName}`,
        time: new Date(),
      };

      console.log("🎯 Adding file message to chat:", newMessage);
      setMessages((prev) => [...prev, newMessage]);
    } catch (error) {
      console.error("❌ Upload error:", error);
      // Remove uploading message and show error
      setMessages((prev) =>
        prev.filter((msg) => msg.id !== uploadingMessage.id)
      );
      alert(
        `Failed to upload file: ${error.response?.data?.error || error.message}`
      );
    } finally {
      setUploading(false);
    }
  };

  const openFileDialog = () => {
    fileInputRef.current?.click();
  };

  const handleFileSelect = (e) => {
    const file = e.target.files[0];
    if (file) {
      console.log("📁 File selected:", file.name, file.type, file.size);
      handleFileUpload(file);
    }
    e.target.value = ""; // Reset input
  };

  const handleKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  const toggleChat = () => {
    setChatOpen((v) => !v);
    if (!chatOpen && unread) setUnread(0);
  };

  const renderMessage = (msg) => {
    if (msg.type === "uploading") {
      return (
        <div style={styles.uploadingMessage}>
          <div style={styles.uploadingSpinner}>⏳</div>
          <div style={styles.msgText}>{msg.text}</div>
        </div>
      );
    }

    if (msg.type === "file" && msg.fileData) {
      return renderFileMessage(msg);
    }

    // return <div style={styles.msgText}>{msg.text}</div>;
    return (
      <div style={styles.msgTextContainer}>
        <div style={styles.msgText}>{msg.text}</div>
        {msg.status && msg.status !== "sent" && (
          <div style={styles.messageStatus}>
            {msg.status === "sending" && "⏳"}
            {msg.status === "failed" && "❌"}
          </div>
        )}
      </div>
    );
  };

  const renderFileMessage = (msg) => {
    const { fileData } = msg;
    const { type, name, size, url, thumbnailUrl, mime } = fileData;

    console.log("🎨 Rendering file message:", {
      type,
      name,
      url,
      thumbnailUrl,
    });

    const formatSize = (bytes) => {
      if (bytes === 0) return "0 Bytes";
      const k = 1024;
      const sizes = ["Bytes", "KB", "MB", "GB"];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
    };

    switch (type) {
      case "image":
        return (
          <div style={styles.imageMessage}>
            <div style={styles.imageContainer}>
              <img
                src={thumbnailUrl || url}
                alt={name}
                style={styles.imagePreview}
                onClick={() => openLightbox(url, "image", name, thumbnailUrl)}
                onLoad={() => console.log("✅ Image loaded successfully")}
                onError={(e) => {
                  console.error("❌ Image failed to load:", e.target.src);
                  e.target.style.display = "none";
                  e.target.nextElementSibling.style.display = "flex";
                }}
                crossOrigin="anonymous"
              />
              {/* Fallback if image fails to load */}
              <div style={{ ...styles.imageError, display: "none" }}>
                <span style={styles.errorIcon}>🖼️</span>
                <small style={styles.errorText}>{name}</small>
                <small style={styles.errorSubtext}>Click to view</small>
              </div>
            </div>
            <div style={styles.imageOverlay}>
              <div style={styles.fileName}>{name}</div>
              <div style={styles.fileSize}>{formatSize(size)}</div>
            </div>
          </div>
        );

      case "video":
        return (
          <div style={styles.videoMessage}>
            <div style={styles.videoContainer}>
              <div style={styles.videoPreview}>
                {thumbnailUrl ? (
                  <img
                    src={thumbnailUrl}
                    alt={name}
                    style={styles.videoThumbnail}
                    onLoad={() => console.log("✅ Video thumbnail loaded")}
                    onError={(e) => {
                      console.error(
                        "❌ Video thumbnail failed to load:",
                        e.target.src
                      );
                      e.target.style.display = "none";
                      e.target.parentNode.querySelector(
                        ".video-placeholder"
                      ).style.display = "flex";
                    }}
                    crossOrigin="anonymous"
                  />
                ) : (
                  <div
                    style={styles.videoPlaceholder}
                    className="video-placeholder"
                  >
                    🎥
                  </div>
                )}

                {/* Hidden placeholder for fallback */}
                <div
                  style={{
                    ...styles.videoPlaceholder,
                    display: thumbnailUrl ? "none" : "flex",
                  }}
                  className="video-placeholder"
                >
                  🎥
                </div>

                <div
                  style={styles.playButton}
                  onClick={() => {
                    console.log("🎬 Opening video in lightbox:", url);
                    openLightbox(url, "video", name, thumbnailUrl); // Updated to use lightbox
                    console.log("🎬 Opening video:", url);
                    window.open(url, "_blank");
                  }}
                  title="Click to play video"
                >
                  <div style={styles.playIcon}>▶️</div>
                </div>

                <div style={styles.videoDuration}>📹 Video</div>
              </div>
              <div style={styles.videoInfo}>
                <div style={styles.fileName}>{name}</div>
                <div style={styles.fileSize}>{formatSize(size)}</div>
              </div>
            </div>
          </div>
        );

      default: // document/other files
        return (
          <div style={styles.documentMessage}>
            <div style={styles.documentContainer}>
              <div style={styles.fileIconContainer}>
                <div style={styles.fileIcon}>{getFileIcon(mime)}</div>
              </div>
              <div style={styles.fileInfo}>
                <div style={styles.fileName}>{name}</div>
                <div style={styles.fileDetails}>
                  <span style={styles.fileSize}>{formatSize(size)}</span>
                  <span style={styles.fileType}>{getFileTypeName(mime)}</span>
                </div>
                <div style={styles.fileActions}>
                  <a
                    href={url}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={styles.downloadBtn}
                    onClick={(e) => {
                      e.stopPropagation();
                      console.log("📥 Downloading file:", url);
                    }}
                  >
                    📥 Download
                  </a>
                  <button
                    style={styles.viewBtn}
                    onClick={() => {
                      console.log("👁️ Viewing file:", url);
                      window.open(url, "_blank");
                    }}
                  >
                    👁️ View
                  </button>
                </div>
              </div>
            </div>
          </div>
        );
    }
  };

  // Enhanced helper functions
  const getFileIcon = (mime) => {
    if (mime?.includes("pdf")) return "📄";
    if (mime?.includes("word") || mime?.includes("document")) return "📝";
    if (mime?.includes("sheet") || mime?.includes("excel")) return "📊";
    if (mime?.includes("presentation") || mime?.includes("powerpoint"))
      return "📽️";
    if (mime?.includes("zip") || mime?.includes("rar") || mime?.includes("7z"))
      return "📦";
    if (mime?.includes("audio")) return "🎵";
    if (mime?.includes("text")) return "📄";
    if (mime?.includes("csv")) return "📊";
    return "📎";
  };

  const getFileTypeName = (mime) => {
    if (mime?.includes("pdf")) return "PDF";
    if (mime?.includes("word")) return "Word";
    if (mime?.includes("document")) return "Document";
    if (mime?.includes("sheet") || mime?.includes("excel"))
      return "Spreadsheet";
    if (mime?.includes("presentation") || mime?.includes("powerpoint"))
      return "Presentation";
    if (mime?.includes("zip")) return "ZIP Archive";
    if (mime?.includes("rar")) return "RAR Archive";
    if (mime?.includes("7z")) return "7Z Archive";
    if (mime?.includes("text")) return "Text";
    if (mime?.includes("csv")) return "CSV";
    return "File";
  };

  return (
    <div style={styles.shell}>
      <div
        style={{
          ...styles.meetingPane,
          width: chatOpen ? "calc(-400px + 100vw)" : "100%",
        }}
      >
        <div ref={containerRef} style={styles.jitsiContainer} />

        {!isConnected && (
          <div style={styles.connectingBanner}>
            <span>🔄 Connecting to meeting...</span>
          </div>
        )}

        <button
          onClick={toggleChat}
          style={styles.fab}
          title="Toggle custom chat"
        >
          💬
          {unread > 0 && <span style={styles.badge}>{unread}</span>}
        </button>
      </div>

      <aside
        style={{
          ...styles.chatPane,
          transform: chatOpen ? "margin-right" : "-400px",
        }}
      >
        <header style={styles.chatHeader}>
          <div style={styles.chatHeaderLeft}>
            <span style={styles.chatTitle}>Chat</span>
            <small style={styles.chatSub}>
              {meetingData?.roomName || roomName}
            </small>
          </div>
          <button
            onClick={toggleChat}
            style={styles.chatCloseBtn}
            title="Close chat"
          >
            ✕
          </button>
        </header>

        <div ref={chatBodyRef} style={styles.chatBody}>
          {messages.length === 0 ? (
            <div style={styles.emptyState}>
              <div style={styles.emptyIcon}>💬</div>
              <div>No messages yet</div>
              <small>Send messages and share files with everyone</small>
            </div>
          ) : (
            <>
              {messages.map((m) => (
                <div
                  key={m.id}
                  style={{
                    ...styles.msgRow,
                    justifyContent: m.me ? "flex-end" : "flex-start",
                  }}
                >
                  <div
                    style={{
                      ...styles.msgBubble,
                      background: m.me ? "#2b62d9" : "#2a2a2a",
                      maxWidth: m.type === "file" ? "280px" : "85%",
                      // Special styling for file messages
                      ...(m.type === "file" && {
                        background: "transparent",
                        padding: "4px",
                        boxShadow: "none",
                      }),
                      ...(m.type === "uploading" && {
                        background: m.me
                          ? "rgba(43, 98, 217, 0.7)"
                          : "rgba(42, 42, 42, 0.7)",
                        opacity: 0.8,
                      }),
                    }}
                  >
                    <div style={styles.msgMeta}>
                      <span style={styles.msgSender}>
                        {m.me ? "Me" : m.from}
                      </span>
                      <span style={styles.msgTime}>
                        {new Intl.DateTimeFormat(undefined, {
                          hour: "2-digit",
                          minute: "2-digit",
                        }).format(m.time)}
                      </span>
                    </div>
                    {renderMessage(m)}
                  </div>
                </div>
              ))}
              {/* Invisible spacer to ensure last message is visible */}
              <div style={{ height: "10px", flexShrink: 0 }} />
            </>
          )}
        </div>

        <footer style={styles.chatFooter}>
          <div style={styles.inputRow}>
            <textarea
              placeholder="Type a message…"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              style={styles.input}
              rows={1}
            />
            <button
              onClick={openFileDialog}
              disabled={uploading}
              style={{
                ...styles.attachBtn,
                opacity: uploading ? 0.6 : 1,
                cursor: uploading ? "not-allowed" : "pointer",
              }}
              title="Upload file, image, or video"
            >
              {uploading ? "⏳" : "📎"}
            </button>
          </div>
          <button
            onClick={sendMessage}
            disabled={!input.trim() || sending}
            style={{
              ...styles.sendBtn,
              opacity: !input.trim() || sending ? 0.5 : 1,
              cursor: !input.trim() || sending ? "not-allowed" : "pointer",
            }}
          >
            {sending ? "..." : "Send"}
          </button>
        </footer>

        <input
          ref={fileInputRef}
          type="file"
          style={{ display: "none" }}
          onChange={handleFileSelect}
          accept="image/*,video/*,.pdf,.doc,.docx,.txt,.zip,.rar"
          multiple={false}
        />
      </aside>
      <Lightbox
        isOpen={lightboxOpen}
        onClose={closeLightbox}
        mediaUrl={lightboxMedia.url}
        mediaType={lightboxMedia.type}
        fileName={lightboxMedia.fileName}
        thumbnailUrl={lightboxMedia.thumbnailUrl}
      />
    </div>
  );
};

// Enhanced Styles for Real Media Display
const styles = {
  shell: {
    display: "grid",
    gridTemplateColumns: "1fr auto",
    height: "100vh",
    background: "#101014",
    color: "#e8e8ea",
    // overflow: "hidden",
    // display: "grid",
    // gridTemplateColumns: "1fr auto",
    display: "flex",
    height: "100vh",
    background: "#101014",
    color: "#e8e8ea",
    overflow: "hidden",
    fontFamily:
      "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
    // Responsive grid layout
    "@media (max-width: 768px)": {
      gridTemplateColumns: "1fr",
    },
  },
  meetingPane: {
    position: "relative",
    height: "100%",
    // overflow: "hidden",
    // Ensure meeting pane takes full width on mobile
    minWidth: 0,
    width: "calc(100vw - 400px)",
    flexShrink: 0,
    paddingTop: "30px",
  },
  jitsiContainer: {
    width: "100%",
    height: "100%",
    minHeight: 500,
    background: "#000",
  },
  connectingBanner: {
    position: "absolute",
    top: 12,
    left: 12,
    background: "rgba(0,0,0,0.8)",
    border: "1px solid rgba(255,255,255,0.1)",
    borderRadius: 8,
    padding: "8px 12px",
    fontSize: 12,
    color: "#fff",
    backdropFilter: "blur(8px)",
    zIndex: 1000,
  },
  fab: {
    position: "absolute",
    right: 16,
    bottom: 16,
    background: "linear-gradient(135deg, #2b62d9, #1e4ba8)",
    color: "#fff",
    border: "none",
    borderRadius: "50%",
    width: 56,
    height: 56,
    fontSize: 20,
    cursor: "pointer",
    boxShadow: "0 8px 24px rgba(43, 98, 217, 0.4)",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    zIndex: 1000,
    transition: "all 0.3s ease",
  },
  badge: {
    position: "absolute",
    top: -4,
    right: -4,
    background: "#e5484d",
    color: "#fff",
    fontSize: 10,
    fontWeight: "bold",
    borderRadius: "50%",
    minWidth: 18,
    height: 18,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    border: "2px solid #101014",
  },
  chatPane: {
    width: "min(400px, 100vw)",
    background: "#15161a",
    borderLeft: "1px solid rgba(255,255,255,0.08)",
    height: "100%",
    display: "flex",
    flexDirection: "column",
    transition: "transform 250ms cubic-bezier(0.4, 0, 0.2, 1)",
    position: "relative",
    zIndex: 100,
    height: "100vh",
    flexShrink: 0,
    transition: "all 0.3s ease",
    // Mobile responsive
    "@media (max-width: 768px)": {
      position: "fixed",
      top: 0,
      right: 0,
      width: "100vw",
      borderLeft: "none",
      borderTop: "1px solid rgba(255,255,255,0.08)",
    },
  },
  chatHeader: {
    padding: "16px 18px",
    padding: "40px 16px 14px",
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    borderBottom: "1px solid rgba(255,255,255,0.08)",
    background: "linear-gradient(135deg, #111216, #0f1014)",
    flexShrink: 0, // Prevent header from shrinking
  },
  chatHeaderLeft: {
    display: "flex",
    flexDirection: "column",
    gap: 2,
  },
  chatTitle: {
    fontWeight: 700,
    fontSize: 15,
    color: "#fff",
  },
  chatSub: {
    opacity: 0.6,
    fontSize: 11,
    color: "#a1a1a1",
  },
  chatCloseBtn: {
    background: "transparent",
    color: "#e8e8ea",
    border: "1px solid rgba(255,255,255,0.15)",
    borderRadius: 6,
    padding: "6px 10px",
    cursor: "pointer",
    fontSize: 12,
    transition: "all 0.2s ease",
  },
  // FIXED: Proper scrolling chat body
  chatBody: {
    flex: 1, // Take remaining space
    overflowY: "auto",
    overflowX: "hidden",
    padding: "16px",
    display: "flex",
    flexDirection: "column",
    gap: 12,
    scrollBehavior: "smooth",
    // Custom scrollbar styling
    scrollbarWidth: "thin",
    scrollbarColor: "#4a4a4a #2a2a2a",
    // Webkit scrollbar styling for Chrome/Safari
    "&::-webkit-scrollbar": {
      width: "6px",
    },
    "&::-webkit-scrollbar-track": {
      background: "#2a2a2a",
      borderRadius: "3px",
    },
    "&::-webkit-scrollbar-thumb": {
      background: "#4a4a4a",
      borderRadius: "3px",
    },
    "&::-webkit-scrollbar-thumb:hover": {
      background: "#5a5a5a",
    },
    // Ensure proper sizing
    minHeight: 0, // Allow flexbox to shrink
    maxHeight: "100%", // Prevent overflow
  },
  emptyState: {
    margin: "auto",
    textAlign: "center",
    opacity: 0.7,
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    gap: 8,
    padding: 20,
  },
  emptyIcon: {
    fontSize: 32,
    marginBottom: 8,
  },
  msgRow: {
    display: "flex",
    marginBottom: 8, // Increased spacing between messages
    alignItems: "flex-end",
    gap: 8,
  },
  msgBubble: {
    maxWidth: "80%", // Reduced max width for better readability
    borderRadius: 16,
    padding: "10px 14px",
    boxShadow: "0 2px 8px rgba(0,0,0,0.3)",
    wordBreak: "break-word",
    // Responsive sizing
    "@media (max-width: 480px)": {
      maxWidth: "90%",
    },
  },
  msgMeta: {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    gap: 8,
    fontSize: 10,
    opacity: 0.8,
    marginBottom: 6,
  },
  msgSender: {
    fontWeight: 600,
    textTransform: "capitalize",
  },
  msgTime: {
    fontVariantNumeric: "tabular-nums",
    fontSize: 9,
    whiteSpace: "nowrap",
  },
  msgText: {
    whiteSpace: "pre-wrap",
    fontSize: 14,
    lineHeight: 1.4,
    color: "#fff",
    wordBreak: "break-word",
  },
  // FIXED: Footer positioning
  chatFooter: {
    borderTop: "1px solid rgba(255,255,255,0.08)",
    padding: 12,
    background: "#121318",
    display: "flex",
    flexDirection: "column",
    gap: 10,
    flexShrink: 0, // Prevent footer from shrinking
    // Responsive padding
    "@media (max-width: 480px)": {
      padding: "8px",
    },
  },
  inputRow: {
    display: "flex",
    gap: 8,
    alignItems: "flex-end",
  },
  input: {
    flex: 1,
    resize: "none",
    minHeight: 40,
    maxHeight: 120,
    borderRadius: 12,
    background: "#0f1014",
    color: "#fff",
    border: "1px solid rgba(255,255,255,0.12)",
    padding: "10px 14px",
    outline: "none",
    fontSize: 14,
    fontFamily: "inherit",
    lineHeight: 1.4,
    // Responsive font size
    "@media (max-width: 480px)": {
      fontSize: "16px", // Prevent zoom on iOS
    },
  },
  attachBtn: {
    background: "#374151",
    color: "#fff",
    border: "none",
    borderRadius: 10,
    width: 40,
    height: 40,
    cursor: "pointer",
    fontSize: 16,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    transition: "all 0.2s ease",
    flexShrink: 0,
  },
  sendBtn: {
    background: "linear-gradient(135deg, #2b62d9, #1e4ba8)",
    color: "#fff",
    border: "none",
    borderRadius: 12,
    padding: "10px 20px",
    fontWeight: 600,
    fontSize: 14,
    cursor: "pointer",
    height: 40,
    transition: "all 0.2s ease",
    flexShrink: 0,
    // Responsive padding
    "@media (max-width: 480px)": {
      padding: "10px 16px",
    },
  },

  // Uploading message styles
  uploadingMessage: {
    display: "flex",
    alignItems: "center",
    gap: 8,
    padding: 8,
    background: "rgba(255,255,255,0.05)",
    borderRadius: 8,
    border: "1px dashed rgba(255,255,255,0.2)",
  },
  uploadingSpinner: {
    fontSize: 16,
    animation: "pulse 1.5s ease-in-out infinite alternate",
  },

  // Image message styles
  imageMessage: {
    borderRadius: 12,
    // overflow: "hidden",
    background: "#1a1a1a",
    maxWidth: "min(280px, 80vw)", // Responsive max width
  },
  imageContainer: {
    position: "relative",
    borderRadius: 12,
    overflow: "hidden",
  },
  imagePreview: {
    width: "100%",
    height: "auto",
    maxHeight: "min(300px, 40vh)", // Responsive max height
    borderRadius: 12,
    cursor: "pointer",
    objectFit: "cover",
    transition: "transform 0.2s ease",
    display: "block",
  },
  imageError: {
    width: "100%",
    height: 150,
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    background: "#2a2a2a",
    borderRadius: 12,
    color: "#888",
    cursor: "pointer",
  },
  errorIcon: {
    fontSize: 32,
    marginBottom: 8,
  },
  errorText: {
    fontSize: 12,
    color: "#fff",
    marginBottom: 4,
  },
  errorSubtext: {
    fontSize: 10,
    color: "#888",
  },
  imageOverlay: {
    position: "absolute",
    bottom: 0,
    left: 0,
    right: 0,
    background: "linear-gradient(transparent, rgba(0,0,0,0.8))",
    padding: "20px 12px 8px",
    color: "white",
    display: "none",
  },

  // Video message styles
  videoMessage: {
    borderRadius: 12,
    // overflow: "hidden",
    background: "#1a1a1a",
    maxWidth: "min(280px, 80vw)", // Responsive max width
  },
  videoContainer: {
    borderRadius: 12,
    overflow: "hidden",
  },
  videoPreview: {
    position: "relative",
    width: "100%",
    height: 180,
    borderRadius: 12,
    // overflow: "hidden",
    background: "#000",
  },
  videoThumbnail: {
    width: "100%",
    height: "100%",
    objectFit: "cover",
    display: "block",
  },
  videoPlaceholder: {
    width: "100%",
    height: "100%",
    background: "linear-gradient(135deg, #333, #555)",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    fontSize: 32,
    color: "#888",
  },
  playButton: {
    position: "absolute",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    background: "rgba(0,0,0,0.8)",
    borderRadius: "50%",
    width: 56,
    height: 56,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    cursor: "pointer",
    transition: "all 0.3s ease",
    border: "3px solid rgba(255,255,255,0.9)",
  },
  playIcon: {
    fontSize: 18,
    marginLeft: 2,
  },
  videoDuration: {
    position: "absolute",
    bottom: 8,
    right: 8,
    background: "rgba(0,0,0,0.7)",
    color: "white",
    padding: "2px 6px",
    borderRadius: 4,
    fontSize: 10,
    fontWeight: 600,
  },
  videoInfo: {
    padding: "8px 12px",
    background: "rgba(255,255,255,0.05)",
  },

  // Document message styles
  documentMessage: {
    maxWidth: "min(280px, 90vw)", // Responsive max width
  },
  documentContainer: {
    display: "flex",
    gap: 12,
    alignItems: "flex-start",
    padding: 12,
    background: "rgba(255,255,255,0.05)",
    borderRadius: 12,
    border: "1px solid rgba(255,255,255,0.1)",
  },
  fileIconContainer: {
    background: "rgba(43, 98, 217, 0.2)",
    borderRadius: 8,
    padding: 8,
    minWidth: 48,
    height: 48,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
  },
  fileIcon: {
    fontSize: 24,
  },
  fileInfo: {
    flex: 1,
    display: "flex",
    flexDirection: "column",
    gap: 4,
    minWidth: 0,
  },
  fileName: {
    fontWeight: 600,
    fontSize: 13,
    color: "#fff",
    wordBreak: "break-word",
    lineHeight: 1.3,
  },
  fileDetails: {
    display: "flex",
    gap: 8,
    alignItems: "center",
    flexWrap: "wrap",
  },
  fileSize: {
    fontSize: 11,
    color: "#999",
  },
  fileType: {
    fontSize: 10,
    color: "#2b62d9",
    background: "rgba(43, 98, 217, 0.2)",
    padding: "2px 6px",
    borderRadius: 4,
    fontWeight: 500,
    textTransform: "uppercase",
  },
  fileActions: {
    display: "flex",
    gap: 8,
    marginTop: 4,
  },
  downloadBtn: {
    color: "#2b62d9",
    textDecoration: "none",
    fontSize: 11,
    fontWeight: 600,
    padding: "4px 8px",
    background: "rgba(43, 98, 217, 0.1)",
    borderRadius: 6,
    transition: "background 0.2s ease",
  },
  viewBtn: {
    color: "#888",
    background: "rgba(255,255,255,0.1)",
    border: "none",
    fontSize: 11,
    fontWeight: 600,
    padding: "4px 8px",
    borderRadius: 6,
    cursor: "pointer",
    transition: "background 0.2s ease",
  },
  msgTextContainer: {
    display: "flex",
    alignItems: "flex-end",
    gap: 4,
  },
  msgText: {
    whiteSpace: "pre-wrap",
    fontSize: 14,
    lineHeight: 1.4,
    color: "#fff",
    wordBreak: "break-word",
    flex: 1,
  },
  messageStatus: {
    fontSize: 10,
    opacity: 0.7,
    flexShrink: 0,
  },
  uploadingMessage: {
    display: "flex",
    alignItems: "center",
    gap: 8,
    padding: 8,
    background: "rgba(255,255,255,0.05)",
    borderRadius: 8,
    border: "1px dashed rgba(255,255,255,0.2)",
  },
  uploadingSpinner: {
    fontSize: 16,
    animation: "pulse 1.5s ease-in-out infinite alternate",
  },
};

export default JitsiWithCustomChat;
