All files / src/features/profile WatchPairingSection.tsx

92.85% Statements 39/42
90% Branches 18/20
100% Functions 6/6
92.85% Lines 39/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144                                                1x 24x 24x 24x 24x 24x   24x 11x 11x 10x   1x 1x         1x 1x     11x       24x 9x     24x 2x 2x 2x 2x 1x   1x 1x 1x         2x       24x 1x 1x 1x 1x 1x       1x       24x   24x 9x             15x                                           5x                                                    
/**
 * WatchPairingSection Component
 * Story W2.1: Pairing Code Backend & Web Frontend
 *
 * Allows organizers to:
 * - Generate a pairing code (AC1) — visible when <2 watches paired
 * - See paired watches with Unpair button (AC4)
 * - View pending code with countdown (AC1, AC3)
 * - See error when max watches reached (AC2)
 */
 
import React, { useState, useEffect, useCallback } from 'react';
import { Alert, Box, Button, Typography } from '@mui/material';
import { BATbernLoader } from '@components/shared/BATbernLoader';
import WatchIcon from '@mui/icons-material/Watch';
import PairingCodeDisplay from './PairingCodeDisplay';
import PairedWatchCard from './PairedWatchCard';
import watchPairingApi from '@/services/api/watchPairingApi';
import type { PairingStatusResponse } from '@/types/watch';
 
interface WatchPairingSectionProps {
  username: string;
}
 
const WatchPairingSection: React.FC<WatchPairingSectionProps> = ({ username }) => {
  const [status, setStatus] = useState<PairingStatusResponse | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isGenerating, setIsGenerating] = useState(false);
  const [unpairingDevice, setUnpairingDevice] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
 
  const loadStatus = useCallback(async () => {
    try {
      const data = await watchPairingApi.getPairingStatus(username);
      setStatus(data);
    } catch (err: unknown) {
      const axiosErr = err as { response?: { status?: number } };
      Iif (axiosErr?.response?.status === 404) {
        // No pairings yet — treat as empty
        setStatus({ pairedWatches: [], pendingCode: null });
      } else {
        // Real error (network failure, 500, etc.) — surface it to the user
        setError('Failed to load pairing status. Please refresh the page.');
        setStatus({ pairedWatches: [], pendingCode: null });
      }
    } finally {
      setIsLoading(false);
    }
  }, [username]);
 
  useEffect(() => {
    loadStatus();
  }, [loadStatus]);
 
  const handleGenerateCode = async () => {
    setIsGenerating(true);
    setError(null);
    try {
      await watchPairingApi.generatePairingCode(username);
      await loadStatus();
    } catch (err: unknown) {
      const axiosErr = err as { response?: { status?: number } };
      if (axiosErr?.response?.status === 409) {
        setError('Maximum 2 watches paired. Unpair a device first.');
      } else E{
        setError('Failed to generate pairing code. Please try again.');
      }
    } finally {
      setIsGenerating(false);
    }
  };
 
  const handleUnpair = async (watchId: string) => {
    setUnpairingDevice(watchId);
    setError(null);
    try {
      await watchPairingApi.unpairWatch(username, watchId);
      await loadStatus();
    } catch {
      setError('Failed to unpair device. Please try again.');
    } finally {
      setUnpairingDevice(null);
    }
  };
 
  const canGenerateCode = status !== null && !status.pendingCode && status.pairedWatches.length < 2;
 
  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 2 }}>
        <BATbernLoader size={48} />
      </Box>
    );
  }
 
  return (
    <Box data-testid="watch-pairing-section">
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
        <WatchIcon />
        <Typography variant="h6">Apple Watch Pairing</Typography>
      </Box>
 
      {error && (
        <Alert severity="error" sx={{ mb: 2 }} data-testid="watch-pairing-error">
          {error}
        </Alert>
      )}
 
      {status?.pendingCode && (
        <Box sx={{ mb: 2 }}>
          <PairingCodeDisplay pendingCode={status.pendingCode} />
        </Box>
      )}
 
      {status?.pairedWatches && status.pairedWatches.length > 0 && (
        <Box sx={{ mb: 2 }}>
          {status.pairedWatches.map((watch) => (
            <PairedWatchCard
              key={watch.id}
              watch={watch}
              onUnpair={handleUnpair}
              isUnpairing={unpairingDevice === watch.id}
            />
          ))}
        </Box>
      )}
 
      {canGenerateCode && (
        <Button
          variant="outlined"
          startIcon={<WatchIcon />}
          onClick={handleGenerateCode}
          disabled={isGenerating}
          data-testid="pair-watch-button"
        >
          {isGenerating ? 'Generating...' : 'Pair Apple Watch'}
        </Button>
      )}
    </Box>
  );
};
 
export default WatchPairingSection;