/**
 * Global PiP (Picture-in-Picture) Overlay
 *
 * This component runs on ALL pages of the application and shows a floating
 * overlay with active sessions and upcoming shifts information.
 *
 * It's completely standalone - fetches its own data and manages its own state.
 */
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import Chip from '@mui/material/Chip';
import Avatar from '@mui/material/Avatar';
import Tooltip from '@mui/material/Tooltip';
import Collapse from '@mui/material/Collapse';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import CssBaseline from '@mui/material/CssBaseline';
import CloseIcon from '@mui/icons-material/Close';
import MinimizeIcon from '@mui/icons-material/Minimize';
import OpenInFullIcon from '@mui/icons-material/OpenInFull';
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
import RefreshIcon from '@mui/icons-material/Refresh';
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
import WorkIcon from '@mui/icons-material/Work';
import CoffeeIcon from '@mui/icons-material/Coffee';
import ScheduleIcon from '@mui/icons-material/Schedule';
import GroupsIcon from '@mui/icons-material/Groups';
import VolumeUpIcon from '@mui/icons-material/VolumeUp';
import VolumeOffIcon from '@mui/icons-material/VolumeOff';
import axios from 'axios';
import { format } from 'date-fns';
import { de } from 'date-fns/locale';
import { getDocumentPipManager, isDocumentPipSupported } from './documentPip';

// Types
interface ActiveSession {
  sessionId: number;
  userId: number;
  userName: string;
  userInitials: string;
  userPhoto: string | null;
  clockInTime: string;
  isOnBreak: boolean;
}

interface UpcomingShift {
  shiftId: number;
  shiftName: string;
  shiftStartTime: string;
  assignedCount: number;
  maxWorkers: number;
  isUserAssigned: boolean;
}

interface PipSettings {
  enabled: boolean;
  collapsed: boolean;
  soundEnabled: boolean;
  showSessions: boolean;
  showUpcoming: boolean;
  position: { x: number; y: number };
  autoPopup: boolean; // Auto-open popup when leaving website
}

// Storage keys
const STORAGE_KEY = 'zeiterfassung_global_pip';
const POSITION_KEY = 'zeiterfassung_pip_position';
const AUTO_PIP_SESSION_KEY = 'zeiterfassung_auto_pip_opened';
const MANUALLY_CLOSED_KEY = 'zeiterfassung_pip_closed'; // Session-only: tracks if user closed PiP this session
const DASHBOARD_LAYOUT_KEY = 'zeiterfassung_dashboard_layout'; // Dashboard settings storage

// Default settings
const DEFAULT_SETTINGS: PipSettings = {
  enabled: true,
  collapsed: false,
  soundEnabled: true,
  showSessions: true,
  showUpcoming: true,
  position: { x: 20, y: 20 },
  autoPopup: true, // Auto-open popup when leaving website
};

// Theme
const theme = createTheme({
  palette: {
    primary: { main: '#1976d2' },
    success: { main: '#2e7d32' },
    warning: { main: '#ed6c02' },
    info: { main: '#0288d1' },
  },
});

// Get default position (bottom-right)
const getDefaultPosition = () => {
  if (typeof window === 'undefined') return { x: 100, y: 100 };
  // Ensure we get valid dimensions (fallback if window not ready)
  const width = window.innerWidth || 1920;
  const height = window.innerHeight || 1080;
  return {
    x: Math.max(20, width - 420),
    y: Math.max(20, height - 350),
  };
};

// Load settings from localStorage
const loadSettings = (): PipSettings => {
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) {
      const parsed = JSON.parse(saved);
      // Always reset enabled to true - we now use sessionStorage for "closed" state
      // This fixes the issue where old localStorage had enabled: false
      return { ...DEFAULT_SETTINGS, ...parsed, enabled: true };
    }
  } catch {}
  return DEFAULT_SETTINGS;
};

// Save settings to localStorage
const saveSettings = (settings: Partial<PipSettings>) => {
  try {
    const current = loadSettings();
    localStorage.setItem(STORAGE_KEY, JSON.stringify({ ...current, ...settings }));
  } catch {}
};

// Load position from localStorage
const loadPosition = () => {
  try {
    const saved = localStorage.getItem(POSITION_KEY);
    if (saved) {
      const pos = JSON.parse(saved);
      // Validate position is reasonable (not negative or off-screen)
      if (typeof pos.x === 'number' && typeof pos.y === 'number' && pos.x >= 0 && pos.y >= 0) {
        return pos;
      }
    }
  } catch {}
  return getDefaultPosition();
};

// Save position to localStorage
const savePosition = (pos: { x: number; y: number }) => {
  try {
    localStorage.setItem(POSITION_KEY, JSON.stringify(pos));
  } catch {}
};

// Check if on mobile
const isMobile = () => {
  if (typeof window === 'undefined') return false;
  return window.innerWidth < 768;
};

// Check if currently on Zeiterfassung page (which has its own PiP)
const isOnZeiterfassungPage = () => {
  return window.location.pathname.includes('/zeiterfassung');
};

// Check if Global PIP is enabled in dashboard settings
const isGlobalPipEnabled = (): boolean => {
  try {
    // First check localStorage (synced from dashboard)
    const saved = localStorage.getItem(DASHBOARD_LAYOUT_KEY);
    if (saved) {
      const parsed = JSON.parse(saved);
      // Check the widgetSettings.pip.globalPipEnabled flag
      if (parsed?.widgetSettings?.pip?.globalPipEnabled !== undefined) {
        return parsed.widgetSettings.pip.globalPipEnabled;
      }
    }
  } catch {}
  // Default to false (disabled by default per user request)
  return false;
};

// Main PiP Component
const GlobalPip: React.FC = () => {
  const [settings, setSettings] = useState<PipSettings>(loadSettings);
  const [show, setShow] = useState(false);
  const [sessions, setSessions] = useState<ActiveSession[]>([]);
  const [upcomingShifts, setUpcomingShifts] = useState<UpcomingShift[]>([]);
  const [loading, setLoading] = useState(false);
  const [position, setPosition] = useState(loadPosition);
  const [isDragging, setIsDragging] = useState(false);

  const elementRef = useRef<HTMLDivElement>(null);
  const dragStartPos = useRef({ x: 0, y: 0 });
  const elementStartPos = useRef({ x: 0, y: 0 });
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const prevSessionsRef = useRef<ActiveSession[]>([]);
  const isFirstFetch = useRef(true);

  // Clamp position to window bounds
  const clampPosition = useCallback((pos: { x: number; y: number }) => {
    if (!elementRef.current) return pos;
    const rect = elementRef.current.getBoundingClientRect();
    return {
      x: Math.max(0, Math.min(window.innerWidth - rect.width, pos.x)),
      y: Math.max(0, Math.min(window.innerHeight - rect.height, pos.y)),
    };
  }, []);

  // Fetch data
  const fetchData = useCallback(async () => {
    if (!settings.enabled) return;

    try {
      setLoading(true);

      const [sessionsRes, shiftsRes] = await Promise.all([
        axios.get('/zeiterfassung/work-sessions/active'),
        axios.get('/zeiterfassung/dashboard/upcoming-shifts', { params: { hours: 6 } }),
      ]);

      // Transform sessions
      const newSessions: ActiveSession[] = sessionsRes.data.map((s: any) => ({
        sessionId: s.session_id,
        userId: s.user_id,
        userName: s.user_name,
        userInitials: s.user_initials,
        userPhoto: s.user_photo,
        clockInTime: s.clock_in_time,
        isOnBreak: s.is_on_break,
      }));

      // Play notification sound on status changes (not on initial load)
      if (settings.soundEnabled && !isFirstFetch.current) {
        const prevSessions = prevSessionsRef.current;
        let shouldPlaySound = false;

        // Check for new sessions (someone clocked in)
        for (const session of newSessions) {
          const prevSession = prevSessions.find(p => p.sessionId === session.sessionId);
          if (!prevSession) {
            // New session - someone clocked in
            shouldPlaySound = true;
            break;
          }
          // Check for break status change
          if (prevSession.isOnBreak !== session.isOnBreak) {
            shouldPlaySound = true;
            break;
          }
        }

        if (shouldPlaySound) {
          try {
            if (!audioRef.current) {
              audioRef.current = new Audio('/sounds/notification.mp3');
              audioRef.current.volume = 0.5;
            }
            audioRef.current.currentTime = 0;
            audioRef.current.play().catch(() => {});
          } catch {}
        }
      }

      // Update refs
      isFirstFetch.current = false;
      prevSessionsRef.current = newSessions;

      setSessions(newSessions);

      // Transform upcoming shifts
      const newShifts: UpcomingShift[] = (shiftsRes.data || []).map((s: any) => ({
        shiftId: s.shiftId,
        shiftName: s.shiftName,
        shiftStartTime: s.shiftStartTime,
        assignedCount: s.assignedCount,
        maxWorkers: s.maxWorkers,
        isUserAssigned: s.isUserAssigned,
      }));
      setUpcomingShifts(newShifts);
    } catch {
      // Silently handle fetch errors
    } finally {
      setLoading(false);
    }
  }, [settings.enabled, settings.soundEnabled]);

  // Initial fetch and interval with visibility check
  useEffect(() => {
    // Check conditions function
    const checkVisibility = () => {
      if (!settings.enabled) {
        return false;
      }

      // Check if Global PIP is enabled in dashboard settings
      if (!isGlobalPipEnabled()) {
        return false;
      }

      if (isOnZeiterfassungPage()) {
        return false;
      }

      if (isMobile()) {
        return false;
      }

      const auth = (window as any).userAuth;
      const hasPermission = auth?.showZeiterfassung;

      if (!hasPermission) {
        return false;
      }

      const closed = sessionStorage.getItem(MANUALLY_CLOSED_KEY) === 'true';
      if (closed) {
        return false;
      }

      return true;
    };

    // Run initial check
    if (checkVisibility()) {
      setShow(true);
      fetchData();
    } else {
      setShow(false);
      // If permission is missing, it might be due to race condition.
      // Retry a few times if userAuth is missing but we're not on the wrong page/mobile
      if (!(window as any).userAuth && !isMobile() && !isOnZeiterfassungPage()) {
         const retryInterval = setInterval(() => {
            if ((window as any).userAuth) {
               if (checkVisibility()) {
                 setShow(true);
                 fetchData();
               }
               clearInterval(retryInterval);
            }
         }, 500);
         // Stop retrying after 5 seconds
         setTimeout(() => clearInterval(retryInterval), 5000);
      }
    }

    // No polling — data is refreshed via FCM push notifications
    const interval: ReturnType<typeof setInterval> | null = null;

    // Listen for localStorage changes (when dashboard settings change in other tabs)
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === DASHBOARD_LAYOUT_KEY) {
        const shouldShow = checkVisibility();
        setShow(shouldShow);
        if (shouldShow && !show) {
          fetchData();
        }
      }
    };
    window.addEventListener('storage', handleStorageChange);

    // Listen for custom event (when dashboard settings change in same tab)
    const handleGlobalPipSettingChange = () => {
      const shouldShow = checkVisibility();
      setShow(shouldShow);
      if (shouldShow && !show) {
        fetchData();
      }
    };
    window.addEventListener('globalPipSettingChanged', handleGlobalPipSettingChange);

    return () => {
      clearInterval(interval);
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('globalPipSettingChanged', handleGlobalPipSettingChange);
    };
  }, [settings.enabled, fetchData, show]);

  // Handle window resize and ensure valid position on mount
  useEffect(() => {
    const handleResize = () => {
      setPosition((prev) => clampPosition(prev));

      // Re-evaluate visibility
      // We shouldn't force show if permission is missing, but if the only reason it was hidden
      // was layout/mobile, and now it's not, we should show it.
      // Ideally we reuse checkVisibility logic but we don't have access to it here easily without moving it out.
      // For now, let's just replicate the critical checks or trust the initial check + state?
      // No, resize changes 'isMobile' result.
      
      const onZeiterfassung = isOnZeiterfassungPage();
      const mobile = isMobile();
      const auth = (window as any).userAuth;
      const hasPermission = auth?.showZeiterfassung;
      const closed = sessionStorage.getItem(MANUALLY_CLOSED_KEY) === 'true';

      if (mobile || onZeiterfassung || !settings.enabled || !hasPermission || closed) {
        setShow(false);
      } else {
        setShow(true);
      }
    };

    // Recalculate position immediately to ensure it's valid
    // This fixes issues where position was calculated before window was ready
    requestAnimationFrame(() => {
      setPosition((prev) => {
        // If position seems invalid (negative or way off screen), reset to default
        if (prev.x < 0 || prev.y < 0 || prev.x > window.innerWidth || prev.y > window.innerHeight) {
          const newPos = getDefaultPosition();
          savePosition(newPos);
          return newPos;
        }
        return clampPosition(prev);
      });
    });

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [clampPosition, settings.enabled, show]);

  // Handle hash change (for Zeiterfassung SPA)
  useEffect(() => {
    const handleHashChange = () => {
      if (isOnZeiterfassungPage()) {
        setShow(false);
      } else if (settings.enabled && !isMobile()) {
        setShow(true);
      }
    };

    window.addEventListener('hashchange', handleHashChange);
    return () => window.removeEventListener('hashchange', handleHashChange);
  }, [settings.enabled]);



  // Dragging handlers
  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    if (e.button !== 0) return;
    e.preventDefault();
    setIsDragging(true);
    dragStartPos.current = { x: e.clientX, y: e.clientY };
    elementStartPos.current = { ...position };
    document.body.style.userSelect = 'none';
    document.body.style.cursor = 'grabbing';
  }, [position]);

  useEffect(() => {
    if (!isDragging) return;

    const handleMouseMove = (e: MouseEvent) => {
      const deltaX = e.clientX - dragStartPos.current.x;
      const deltaY = e.clientY - dragStartPos.current.y;
      const newPos = clampPosition({
        x: elementStartPos.current.x + deltaX,
        y: elementStartPos.current.y + deltaY,
      });
      setPosition(newPos);
    };

    const handleMouseUp = () => {
      setIsDragging(false);
      document.body.style.userSelect = '';
      document.body.style.cursor = '';
      savePosition(position);
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDragging, clampPosition, position]);

  // Update settings
  const updateSettings = useCallback((updates: Partial<PipSettings>) => {
    setSettings((prev) => {
      const newSettings = { ...prev, ...updates };
      saveSettings(newSettings);
      return newSettings;
    });
  }, []);

  // Handle close - just hide for this session, don't permanently disable
  const handleClose = useCallback(() => {
    sessionStorage.setItem(MANUALLY_CLOSED_KEY, 'true');
    setShow(false);
  }, []);

  // Handle expand - navigate to Zeiterfassung dashboard
  const handleExpand = useCallback(() => {
    window.location.href = '/zeiterfassung?tab=dashboard';
  }, []);

  // Handle pop-out - open Document PiP (floating window attached to current tab)
  const handlePopOut = useCallback(async () => {
    // Use Document PiP (floating window attached to current tab)
    // When the tab is closed, the PiP window also closes
    if (isDocumentPipSupported()) {
      const pipManager = getDocumentPipManager();
      const opened = await pipManager.open();
      if (opened) {
        handleClose();
      }
    }
  }, [handleClose]);

  // Handle collapse toggle
  const handleToggleCollapse = useCallback(() => {
    updateSettings({ collapsed: !settings.collapsed });
  }, [settings.collapsed, updateSettings]);

  // Handle sound toggle
  const handleToggleSound = useCallback(() => {
    updateSettings({ soundEnabled: !settings.soundEnabled });
  }, [settings.soundEnabled, updateSettings]);

  // Auto-open Document PiP after first click anywhere on the page (Option 3)
  // This works because Document PiP requires a user gesture, and any click counts
  useEffect(() => {
    // Skip if:
    // - Not on a page where PiP should show
    // - Document PiP not supported
    // - Already auto-opened this session
    // - PiP is disabled in settings
    // - On Zeiterfassung page (has its own PiP)
    if (!show) return;
    if (!isDocumentPipSupported()) return;
    if (sessionStorage.getItem(AUTO_PIP_SESSION_KEY) === 'true') return;
    if (!settings.enabled || !settings.autoPopup) return;
    if (isOnZeiterfassungPage()) return;

    let hasTriggered = false;

    const handleFirstClick = async () => {
      if (hasTriggered) return;
      hasTriggered = true;

      // Remove the listener immediately
      document.removeEventListener('click', handleFirstClick, true);

      // Small delay to ensure click event is fully processed
      await new Promise((resolve) => setTimeout(resolve, 100));

      try {
        const pipManager = getDocumentPipManager();
        const opened = await pipManager.open();

        if (opened) {
          // Mark as opened so we don't keep trying
          sessionStorage.setItem(AUTO_PIP_SESSION_KEY, 'true');
          // Close the in-page overlay since we have Document PiP now
          handleClose();
        }
      } catch {
        // Silently handle errors
      }
    };

    // Use capture phase to catch click before any other handlers might prevent it
    document.addEventListener('click', handleFirstClick, true);

    return () => {
      document.removeEventListener('click', handleFirstClick, true);
    };
  }, [show, settings.enabled, settings.autoPopup, handleClose]);

  // Don't render if not showing
  if (!show) return null;

  const workingCount = sessions.filter((s) => !s.isOnBreak).length;
  const breakCount = sessions.filter((s) => s.isOnBreak).length;

  return (
    <Paper
      ref={elementRef}
      elevation={8}
      sx={{
        position: 'fixed',
        left: position.x,
        top: position.y,
        width: 380,
        maxHeight: settings.collapsed ? 'auto' : 400,
        zIndex: 9999,
        borderRadius: 2,
        overflow: 'hidden',
        opacity: isDragging ? 0.9 : 1,
        transition: isDragging ? 'none' : 'opacity 0.2s',
        boxShadow: '0 8px 32px rgba(0,0,0,0.2)',
      }}
    >
      {/* Header */}
      <Box
        onMouseDown={handleMouseDown}
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          px: 1.5,
          py: 1,
          bgcolor: 'primary.main',
          color: 'white',
          cursor: isDragging ? 'grabbing' : 'grab',
        }}
      >
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <DragIndicatorIcon fontSize="small" sx={{ opacity: 0.7 }} />
          <Typography variant="subtitle2" fontWeight="bold">
            Live-Übersicht
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
          <Tooltip title="Aktualisieren">
            <IconButton size="small" onClick={fetchData} sx={{ color: 'white' }}>
              <RefreshIcon
                fontSize="small"
                sx={{
                  animation: loading ? 'spin 1s linear infinite' : 'none',
                  '@keyframes spin': {
                    '0%': { transform: 'rotate(0deg)' },
                    '100%': { transform: 'rotate(360deg)' },
                  },
                }}
              />
            </IconButton>
          </Tooltip>
          <Tooltip title={settings.soundEnabled ? 'Ton aus' : 'Ton an'}>
            <IconButton size="small" onClick={handleToggleSound} sx={{ color: 'white' }}>
              {settings.soundEnabled ? <VolumeUpIcon fontSize="small" /> : <VolumeOffIcon fontSize="small" />}
            </IconButton>
          </Tooltip>
          <Tooltip title={settings.collapsed ? 'Erweitern' : 'Minimieren'}>
            <IconButton size="small" onClick={handleToggleCollapse} sx={{ color: 'white' }}>
              <MinimizeIcon fontSize="small" />
            </IconButton>
          </Tooltip>
          <Tooltip title="Zum Dashboard">
            <IconButton size="small" onClick={handleExpand} sx={{ color: 'white' }}>
              <OpenInFullIcon fontSize="small" />
            </IconButton>
          </Tooltip>
          <Tooltip title="Als Popup öffnen">
            <IconButton size="small" onClick={handlePopOut} sx={{ color: 'white' }}>
              <OpenInNewIcon fontSize="small" />
            </IconButton>
          </Tooltip>
          <Tooltip title="Schließen">
            <IconButton size="small" onClick={handleClose} sx={{ color: 'white' }}>
              <CloseIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        </Box>
      </Box>

      {/* Collapsed View */}
      {settings.collapsed && (
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-around',
            py: 1,
            px: 2,
            bgcolor: 'grey.100',
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <WorkIcon fontSize="small" color="success" />
            <Typography variant="body2" fontWeight="bold">
              {workingCount}
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <CoffeeIcon fontSize="small" color="warning" />
            <Typography variant="body2" fontWeight="bold">
              {breakCount}
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <ScheduleIcon fontSize="small" color="info" />
            <Typography variant="body2" fontWeight="bold">
              {upcomingShifts.length}
            </Typography>
          </Box>
        </Box>
      )}

      {/* Expanded View */}
      <Collapse in={!settings.collapsed}>
        <Box sx={{ maxHeight: 340, overflow: 'auto' }}>
          {/* Active Sessions */}
          {settings.showSessions && (
            <>
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  px: 1.5,
                  py: 0.75,
                  bgcolor: 'success.light',
                  opacity: 0.2,
                  borderBottom: '1px solid',
                  borderColor: 'divider',
                }}
              />
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  px: 1.5,
                  py: 0.75,
                  bgcolor: '#e8f5e9',
                  borderBottom: '1px solid',
                  borderColor: 'divider',
                }}
              >
                <Typography variant="caption" fontWeight="bold" color="success.dark">
                  AKTIV ({sessions.length})
                </Typography>
                <Box sx={{ display: 'flex', gap: 1 }}>
                  <Chip
                    size="small"
                    icon={<WorkIcon sx={{ fontSize: 12 }} />}
                    label={workingCount}
                    color="success"
                    sx={{ height: 20, fontSize: '0.7rem' }}
                  />
                  {breakCount > 0 && (
                    <Chip
                      size="small"
                      icon={<CoffeeIcon sx={{ fontSize: 12 }} />}
                      label={breakCount}
                      color="warning"
                      sx={{ height: 20, fontSize: '0.7rem' }}
                    />
                  )}
                </Box>
              </Box>

              <List dense disablePadding>
                {sessions.slice(0, 5).map((session) => (
                  <ListItem
                    key={session.sessionId}
                    sx={{
                      py: 0.5,
                      px: 1.5,
                      borderBottom: '1px solid',
                      borderColor: 'divider',
                    }}
                  >
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, width: '100%' }}>
                      <Avatar
                        src={session.userPhoto || undefined}
                        sx={{
                          width: 24,
                          height: 24,
                          fontSize: '0.65rem',
                          bgcolor: session.isOnBreak ? 'warning.main' : 'success.main',
                        }}
                      >
                        {session.userInitials}
                      </Avatar>
                      <Typography variant="caption" fontWeight="medium" sx={{ flex: 1 }} noWrap>
                        {session.userName}
                      </Typography>
                      {session.isOnBreak ? (
                        <CoffeeIcon sx={{ fontSize: 14, color: 'warning.main' }} />
                      ) : (
                        <WorkIcon sx={{ fontSize: 14, color: 'success.main' }} />
                      )}
                      <Typography variant="caption" color="text.secondary">
                        {format(new Date(session.clockInTime), 'HH:mm', { locale: de })}
                      </Typography>
                    </Box>
                  </ListItem>
                ))}
                {sessions.length > 5 && (
                  <ListItem sx={{ py: 0.5, px: 1.5, justifyContent: 'center' }}>
                    <Typography variant="caption" color="text.secondary">
                      +{sessions.length - 5} weitere
                    </Typography>
                  </ListItem>
                )}
                {sessions.length === 0 && (
                  <ListItem sx={{ py: 1, px: 1.5, justifyContent: 'center' }}>
                    <Typography variant="caption" color="text.secondary">
                      Keine aktiven Sitzungen
                    </Typography>
                  </ListItem>
                )}
              </List>
            </>
          )}

          {/* Upcoming Shifts */}
          {settings.showUpcoming && (
            <>
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  px: 1.5,
                  py: 0.75,
                  bgcolor: '#e3f2fd',
                  borderBottom: '1px solid',
                  borderColor: 'divider',
                }}
              >
                <Typography variant="caption" fontWeight="bold" color="info.dark">
                  KOMMEND ({upcomingShifts.length})
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  nächste 6h
                </Typography>
              </Box>

              <List dense disablePadding>
                {upcomingShifts.slice(0, 4).map((shift) => (
                  <ListItem
                    key={shift.shiftId}
                    sx={{
                      py: 0.5,
                      px: 1.5,
                      borderBottom: '1px solid',
                      borderColor: 'divider',
                      bgcolor: shift.isUserAssigned ? '#e3f2fd' : 'transparent',
                    }}
                  >
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, width: '100%' }}>
                      <Typography variant="caption" fontWeight="bold" sx={{ minWidth: 80 }}>
                        {shift.shiftStartTime}
                      </Typography>
                      <Typography variant="caption" sx={{ flex: 1 }} noWrap>
                        {shift.shiftName}
                      </Typography>
                      <Chip
                        size="small"
                        icon={<GroupsIcon sx={{ fontSize: 10 }} />}
                        label={`${shift.assignedCount}/${shift.maxWorkers}`}
                        color={
                          shift.assignedCount >= shift.maxWorkers
                            ? 'success'
                            : shift.assignedCount >= shift.maxWorkers / 2
                            ? 'warning'
                            : 'error'
                        }
                        sx={{ height: 18, fontSize: '0.65rem' }}
                      />
                      {shift.isUserAssigned && (
                        <Chip
                          size="small"
                          label="DU"
                          color="primary"
                          sx={{ height: 18, fontSize: '0.65rem' }}
                        />
                      )}
                    </Box>
                  </ListItem>
                ))}
                {upcomingShifts.length > 4 && (
                  <ListItem sx={{ py: 0.5, px: 1.5, justifyContent: 'center' }}>
                    <Typography variant="caption" color="text.secondary">
                      +{upcomingShifts.length - 4} weitere
                    </Typography>
                  </ListItem>
                )}
                {upcomingShifts.length === 0 && (
                  <ListItem sx={{ py: 1, px: 1.5, justifyContent: 'center' }}>
                    <Typography variant="caption" color="text.secondary">
                      Keine Schichten in den nächsten 6 Stunden
                    </Typography>
                  </ListItem>
                )}
              </List>
            </>
          )}
        </Box>
      </Collapse>
    </Paper>
  );
};

// App wrapper with theme
const App: React.FC = () => {
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <GlobalPip />
    </ThemeProvider>
  );
};

// Mount the component
const mountGlobalPip = () => {
  // Check if user has Zeiterfassung permission
  const hasPermission = (window as any).userAuth?.showZeiterfassung;
  if (!hasPermission) {
    return;
  }

  // Don't mount on mobile
  if (isMobile()) {
    return;
  }

  // Create mount point
  let container = document.getElementById('global-pip-root');
  if (!container) {
    container = document.createElement('div');
    container.id = 'global-pip-root';
    document.body.appendChild(container);
  }

  const root = createRoot(container);
  root.render(<App />);
};

// Wait for DOM and userAuth to be ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    // Small delay to ensure userAuth is set
    setTimeout(mountGlobalPip, 100);
  });
} else {
  setTimeout(mountGlobalPip, 100);
}
