// ==========================================
// 全域工具：企業通訊懸浮球 (FloatingMessenger.jsx)
// ==========================================
// 宣告需要用到的 React Hooks (確保在獨立檔案中也能抓到)
const { useState, useEffect, useRef } = React;

const FloatingMessenger = ({ session, memberData, supabase }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [currentView, setCurrentView] = useState('home'); // 'home', 'chat'
  const [activeContact, setActiveContact] = useState(null);
  const [input, setInput] = useState('');
  
  const [directory, setDirectory] = useState([]);
  const [messages, setMessages] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  
  const messagesEndRef = useRef(null);
  const myId = session?.user?.id;

  // 1. 初始化撈取資料 (通訊錄與歷史訊息)
  useEffect(() => {
    if (!isOpen || !myId) return;
    
    const fetchData = async () => {
      const { data: dirData } = await supabase.from('vw_chat_directory').select('*');
      if (dirData) setDirectory(dirData);

      const { data: msgData } = await supabase.from('messages')
        .select('*')
        .or(`sender_id.eq.${myId},receiver_id.eq.${myId}`)
        .order('created_at', { ascending: true });
      if (msgData) setMessages(msgData);
    };
    
    fetchData();
  }, [isOpen, myId]);

  // 2. Realtime 即時推播監聽 (加上防重複機制)
  useEffect(() => {
    if (!myId) return;
    const channel = supabase.channel('realtime:messages')
      .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages' }, (payload) => {
        const newMsg = payload.new;
        if (newMsg.sender_id === myId || newMsg.receiver_id === myId) {
          setMessages(prev => {
            // 💡 檢查訊息是否已經存在 (防重複)
            if (prev.some(m => m.id === newMsg.id)) return prev;
            return [...prev, newMsg];
          });
        }
      })
      .subscribe();
    return () => supabase.removeChannel(channel);
  }, [myId]);

  // 3. 自動滾動到最新訊息
  useEffect(() => {
    if (currentView === 'chat') {
      messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, currentView]);

  // 🌟 修正傳送訊息邏輯：強制回傳並即時更新畫面
  const handleSend = async () => {
    if (!input.trim() || !activeContact) return;
    const msgText = input.trim();
    setInput(''); 

    // 加入 .select() 強制資料庫回傳剛寫入的那筆資料
    const { data, error } = await supabase.from('messages').insert([{
      sender_id: myId,
      receiver_id: activeContact.id,
      content: msgText
    }]).select();

    if (error) {
      alert('傳送失敗：' + error.message);
    } else if (data && data.length > 0) {
      // 💡 主動將剛發送成功的訊息塞入目前的對話列表中
      setMessages(prev => {
        if (prev.some(m => m.id === data[0].id)) return prev; // 防重複
        return [...prev, data[0]];
      });
    }
  };

  // 核心邏輯：聯絡人分類計算 (動態版)
  const getContactGroups = () => {
    // 動態判斷自己是否為無權限菜鳥
    const myRoles = Object.keys(memberData || {}).filter(k => k.endsWith('_role'));
    const hasNoPermissions = myRoles.every(roleKey => memberData[roleKey] === 'none' || !memberData[roleKey]);

    if (hasNoPermissions) return { recent: [], recommended: [], searchResults: [] };

    const others = directory.filter(c => c.id !== myId);
    
    // 跨部門全局搜尋
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      const results = others.filter(c => 
        (c.name || '').toLowerCase().includes(q) || 
        (c.department || '').toLowerCase().includes(q) || 
        (c.emp_no || '').toLowerCase().includes(q)
      );
      return { recent: [], recommended: [], searchResults: results };
    }

    // A. 計算最近對話
    const interactedIds = [...new Set(messages.map(m => m.sender_id === myId ? m.receiver_id : m.sender_id))];
    const recent = others.filter(c => interactedIds.includes(c.id));

    // B. 計算同部門推薦 (動態比對是否有重疊的有效權限)
    const recommended = others.filter(c => {
      if (c.department !== memberData.department || !c.department) return false;
      
      let hasSharedRole = false;
      if (c.roles) {
        Object.keys(c.roles).forEach(roleKey => {
          if (c.roles[roleKey] !== 'none' && memberData[roleKey] !== 'none' && memberData[roleKey] !== undefined) {
            hasSharedRole = true;
          }
        });
      }
      return hasSharedRole;
    }).filter(c => !interactedIds.includes(c.id)); 

    return { recent, recommended, searchResults: [] };
  };

  const groups = getContactGroups();

  // 動態判斷自己是否為無權限菜鳥 (給 UI 使用)
  const myRoles = Object.keys(memberData || {}).filter(k => k.endsWith('_role'));
  const hasNoPermissions = myRoles.every(roleKey => memberData[roleKey] === 'none' || !memberData[roleKey]);

  const openChat = (contact) => {
    setActiveContact(contact);
    setCurrentView('chat');
  };

  const ContactItem = ({ contact }) => (
    <div onClick={() => openChat(contact)} className="flex items-center gap-3 p-2 hover:bg-slate-100 cursor-pointer rounded-lg transition-colors">
      <div className="w-10 h-10 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center font-bold shrink-0 shadow-sm border border-blue-200">
        {contact.name ? contact.name.charAt(0) : '?'}
      </div>
      <div className="flex-1 overflow-hidden">
        <div className="font-bold text-sm text-slate-800 flex justify-between items-center">
          <span className="truncate">{contact.name}</span>
          <span className="text-[10px] text-slate-400 font-mono shrink-0">{contact.emp_no}</span>
        </div>
        <div className="text-xs text-slate-500 truncate mt-0.5">
          {contact.department || '未分配部門'} 
        </div>
      </div>
    </div>
  );

  return (
    <div className="fixed bottom-6 right-6 z-[100]">
      
      {/* 聊天視窗 (Chat Window) */}
      <div 
        className={`absolute bottom-[calc(100%+16px)] right-0 bg-white rounded-2xl shadow-2xl border border-slate-200 overflow-hidden transition-all duration-300 origin-bottom-right w-[350px] sm:w-[380px] flex flex-col h-[550px] ${
          isOpen ? 'opacity-100 scale-100 pointer-events-auto' : 'opacity-0 scale-0 pointer-events-none'
        }`}
      >
        
        {/* 首頁視圖 (Home View) */}
        {currentView === 'home' && (
          <div className="flex flex-col h-full bg-slate-50">
            <div className="bg-slate-900 p-4 flex items-center justify-between text-white shrink-0 shadow-md z-10">
              <div className="flex items-center gap-2">
                <Icon name="message-circle" className="w-5 h-5 text-blue-400" />
                <h3 className="font-bold text-sm tracking-wide">企業內部通訊</h3>
              </div>
              <button onClick={() => setIsOpen(false)} className="text-slate-400 hover:text-white p-1">
                <Icon name="x" className="w-5 h-5" />
              </button>
            </div>
            
            <div className="p-4 flex-1 overflow-y-auto">
              {hasNoPermissions ? (
                <div className="text-center py-10 flex flex-col items-center">
                  <div className="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mb-4">
                    <Icon name="alert-circle" className="w-8 h-8 text-slate-400"/>
                  </div>
                  <div className="text-slate-700 font-bold mb-2">通訊功能未開通</div>
                  <p className="text-xs text-slate-500 px-4 leading-relaxed">
                    您目前尚未具備任何系統的操作權限，無法使用內部通訊功能。請聯繫所屬部門主管或人資單位為您配置權限。
                  </p>
                </div>
              ) : (
                <>
                  <div className="relative mb-5">
                    <Icon name="search" className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                    <input type="text" value={searchQuery} onChange={e => setSearchQuery(e.target.value)} placeholder="搜尋工號、姓名、部門發起對話..." className="w-full pl-9 pr-3 py-2.5 bg-white border border-slate-200 rounded-xl text-sm focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 shadow-sm" />
                  </div>

                  {searchQuery.trim() ? (
                    <div>
                      <div className="text-xs font-bold text-slate-400 mb-2 border-b pb-1">搜尋結果</div>
                      {groups.searchResults.length === 0 ? <div className="text-center text-xs text-slate-400 py-6">查無符合的同事</div> : groups.searchResults.map(c => <ContactItem key={c.id} contact={c} />)}
                    </div>
                  ) : (
                    <div className="space-y-6">
                      {groups.recent.length > 0 && (
                        <div>
                          <div className="text-xs font-bold text-slate-400 mb-2 flex items-center gap-1 border-b pb-1"><Icon name="history" className="w-3 h-3"/> 最近對話</div>
                          {groups.recent.map(c => <ContactItem key={c.id} contact={c} />)}
                        </div>
                      )}
                      {groups.recommended.length > 0 && (
                        <div>
                          <div className="text-xs font-bold text-slate-400 mb-2 flex items-center justify-between border-b pb-1">
                            <span className="flex items-center gap-1"><Icon name="users" className="w-3 h-3"/> 推薦聯絡人</span>
                            <span className="font-normal text-[10px] bg-slate-200 px-1.5 py-0.5 rounded text-slate-600">{memberData.department}</span>
                          </div>
                          {groups.recommended.map(c => <ContactItem key={c.id} contact={c} />)}
                        </div>
                      )}
                      {groups.recent.length === 0 && groups.recommended.length === 0 && (
                        <div className="text-center py-8 text-slate-400 text-xs">
                          目前無近期對話紀錄。<br/>請在上方搜尋列尋找同事發起對話。
                        </div>
                      )}
                    </div>
                  )}
                </>
              )}
            </div>
          </div>
        )}

        {/* 聊天視窗 (Chat View) */}
        {currentView === 'chat' && activeContact && (
          <div className="flex flex-col h-full bg-slate-50">
            <div className="bg-slate-900 p-3 flex items-center text-white shrink-0 gap-3 shadow-md z-10">
              <button onClick={() => setCurrentView('home')} className="text-slate-300 hover:text-white p-1 hover:bg-slate-800 rounded transition-colors">
                <Icon name="chevron-left" className="w-5 h-5" />
              </button>
              <div className="flex-1">
                <div className="font-bold text-sm leading-tight">{activeContact.name}</div>
                <div className="text-[10px] text-slate-400">{activeContact.department || '未分配部門'} | {activeContact.emp_no}</div>
              </div>
            </div>

            <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-slate-100/50">
              {messages.filter(m => (m.sender_id === activeContact.id && m.receiver_id === myId) || (m.sender_id === myId && m.receiver_id === activeContact.id)).map((msg) => {
                const isMe = msg.sender_id === myId;
                return (
                  <div key={msg.id} className={`flex ${isMe ? 'justify-end' : 'justify-start'}`}>
                    <div className={`max-w-[75%] rounded-2xl px-3 py-2.5 text-sm shadow-sm whitespace-pre-wrap leading-relaxed ${isMe ? 'bg-blue-600 text-white rounded-br-sm' : 'bg-white border border-slate-200 text-slate-800 rounded-bl-sm'}`}>
                      {msg.content}
                      <div className={`text-[9px] mt-1 text-right ${isMe ? 'text-blue-200' : 'text-slate-400'}`}>
                        {new Date(msg.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
                      </div>
                    </div>
                  </div>
                )
              })}
              <div ref={messagesEndRef} />
            </div>

            <div className="p-3 bg-white border-t border-slate-200 shrink-0">
              <div className="flex items-end gap-2 bg-slate-50 rounded-xl border border-slate-200 p-1 focus-within:border-blue-400 focus-within:ring-1 focus-within:ring-blue-400 transition-all">
                <textarea 
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  onKeyDown={(e) => { if(e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }}
                  placeholder="輸入訊息..."
                  className="flex-1 max-h-24 min-h-[40px] bg-transparent border-none focus:ring-0 resize-none px-3 py-2 text-sm text-slate-700 outline-none"
                  rows="1"
                />
                <button onClick={handleSend} disabled={!input.trim()} className="p-2 bg-blue-600 hover:bg-blue-500 disabled:bg-slate-300 text-white rounded-lg transition-colors mb-0.5 mr-0.5 shadow-sm">
                  <Icon name="send" className="w-4 h-4" />
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      <button onClick={() => setIsOpen(!isOpen)} className={`w-14 h-14 rounded-full flex items-center justify-center shadow-xl transition-all duration-300 hover:scale-110 relative z-10 ${isOpen ? 'bg-slate-800 text-white hover:bg-slate-700' : 'bg-blue-600 hover:bg-blue-500 text-white shadow-blue-500/30'}`}>
        {isOpen ? <Icon name="x" className="w-6 h-6" /> : <Icon name="message-circle" className="w-6 h-6" />}
      </button>
    </div>
  );
}

// 將元件掛載到全域 window 上，讓其他 HTML 檔案可以抓取到
window.FloatingMessenger = FloatingMessenger;