import { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { io } from 'socket.io-client';
import { useAuth } from './AuthContext';

const SocketContext = createContext(null);

export function SocketProvider({ children }) {
  const { user } = useAuth();
  const [socket, setSocket] = useState(null);
  const [notifications, setNotifications] = useState([]);
  const [unreadCount, setUnreadCount] = useState(0);

  useEffect(() => {
    if (!user) return;
    const newSocket = io('/', { auth: { userId: user.id }, transports: ['websocket', 'polling'] });
    newSocket.on('connect', () => console.log('Socket connected'));
    newSocket.on('notification:new', (notif) => {
      setNotifications(prev => [notif, ...prev]);
      setUnreadCount(prev => prev + 1);
    });
    newSocket.on('message:new', (msg) => {
      window.dispatchEvent(new CustomEvent('new-message', { detail: msg }));
    });
    newSocket.on('booking:status', (data) => {
      window.dispatchEvent(new CustomEvent('booking-status', { detail: data }));
    });
    setSocket(newSocket);
    return () => { newSocket.close(); };
  }, [user]);

  const joinBooking = useCallback((bookingId) => { socket?.emit('join:booking', bookingId); }, [socket]);
  const sendMessage = useCallback((bookingId, content, type = 'text') => {
    socket?.emit('send:message', { bookingId, content, type });
  }, [socket]);
  const markRead = useCallback((id) => {
    setNotifications(prev => prev.map(n => n._id === id ? { ...n, read: true } : n));
    setUnreadCount(prev => Math.max(0, prev - 1));
  }, []);
  const markAllRead = useCallback(() => {
    setNotifications(prev => prev.map(n => ({ ...n, read: true })));
    setUnreadCount(0);
  }, []);

  return (
    <SocketContext.Provider value={{ socket, notifications, unreadCount, joinBooking, sendMessage, markRead, markAllRead }}>
      {children}
    </SocketContext.Provider>
  );
}

export function useSocket() {
  const ctx = useContext(SocketContext);
  if (!ctx) throw new Error('useSocket must be used within SocketProvider');
  return ctx;
}