import { useState, useEffect } from 'react';
import { useSocket } from '../contexts/SocketContext.jsx';
import { api } from '../utils/api.js';

export default function GlobalBar({ isMobile, showSidebar }) {
  const { connected } = useSocket();
  const [settings, setSettings] = useState({ app_name: 'jama', logo_url: '' });

  useEffect(() => {
    api.getSettings().then(({ settings }) => setSettings(settings)).catch(() => {});
    const handler = () => api.getSettings().then(({ settings }) => setSettings(settings)).catch(() => {});
    window.addEventListener('jama:settings-changed', handler);
    return () => window.removeEventListener('jama:settings-changed', handler);
  }, []);

  const appName = settings.app_name || 'jama';
  const logoUrl = settings.logo_url;

  // On mobile: show bar only when sidebar is visible (chat list view)
  // On desktop: always show
  if (isMobile && !showSidebar) return null;

  return (
    <div className="global-bar">
      <div className="global-bar-brand">
        <img
          src={logoUrl || '/icons/jama.png'}
          alt={appName}
          className="global-bar-logo"
        />
        <span className="global-bar-title">{appName}</span>
      </div>
      {!connected && (
        <span className="global-bar-offline" title="Offline">
          <span className="offline-dot" />
          <span className="offline-label">Offline</span>
        </span>
      )}
    </div>
  );
}
