All files / src/screens PlayMode.tsx

0% Statements 0/45
0% Branches 0/40
0% Functions 0/14
0% Lines 0/44

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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { useState, useCallback, useEffect } from 'react'
import { X, ChevronLeft, ChevronRight } from 'lucide-react'
import { toast } from 'sonner'
import { api } from '../api/client'
import type { RecipeDetail } from '../api/client'
import { useTimers } from '../hooks/useTimers'
import { useWakeLock } from '../hooks/useWakeLock'
import TimerPanel from '../components/TimerPanel'
import { cn } from '../lib/utils'
import { unlockAudio, playTimerAlert } from '../lib/audio'
 
interface PlayModeProps {
  recipe: RecipeDetail
  onExit: () => void
}
 
export default function PlayMode({ recipe, onExit }: PlayModeProps) {
  const [currentStep, setCurrentStep] = useState(0)
  const [aiAvailable, setAiAvailable] = useState(false)
 
  // Fetch AI availability on mount
  useEffect(() => {
    api.ai.status().then((status) => {
      setAiAvailable(status.available)
    }).catch(() => {
      setAiAvailable(false)
    })
  }, [])
 
  // Get instructions array
  const instructions =
    recipe.instructions.length > 0
      ? recipe.instructions
      : recipe.instructions_text
        ? recipe.instructions_text.split('\n').filter((s) => s.trim())
        : []
 
  const totalSteps = instructions.length
 
  // Timer completion handler
  const handleTimerComplete = useCallback(
    (timer: { label: string }) => {
      // Play audio alert
      playTimerAlert()
 
      // Show toast notification
      toast.success(`Timer complete: ${timer.label}`, {
        duration: 10000,
      })
 
      // Show browser notification (may include system sound)
      try {
        if ('Notification' in window && Notification.permission === 'granted') {
          new Notification('Timer Complete!', {
            body: timer.label,
            icon: '/favicon.ico',
          })
        }
      } catch {
        // Notification not supported or blocked
      }
    },
    []
  )
 
  const timers = useTimers(handleTimerComplete)
 
  // Keep screen awake during Play Mode
  useWakeLock()
 
  // Request notification permission and unlock audio on mount
  useEffect(() => {
    if ('Notification' in window && Notification.permission === 'default') {
      Notification.requestPermission()
    }
    // Unlock audio for iOS (requires user interaction context)
    // This works because entering Play Mode requires a button click
    unlockAudio()
  }, [])
 
  const currentInstruction = instructions[currentStep] || ''
  const progress = totalSteps > 0 ? ((currentStep + 1) / totalSteps) * 100 : 0
 
  const handlePrevious = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1)
    }
  }
 
  const handleNext = () => {
    if (currentStep < totalSteps - 1) {
      setCurrentStep(currentStep + 1)
    }
  }
 
  // Keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
        handlePrevious()
      } else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
        handleNext()
      } else if (e.key === 'Escape') {
        onExit()
      }
    }
 
    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [currentStep, totalSteps, onExit])
 
  if (totalSteps === 0) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center bg-background p-4">
        <p className="mb-4 text-center text-muted-foreground">
          No instructions available for this recipe.
        </p>
        <button
          onClick={onExit}
          className="rounded-lg bg-primary px-4 py-2 text-primary-foreground"
        >
          Exit
        </button>
      </div>
    )
  }
 
  return (
    <div className="flex min-h-screen flex-col bg-background">
      {/* Header with progress */}
      <div className="relative border-b border-border">
        {/* Progress bar */}
        <div className="h-1 bg-muted">
          <div
            className="h-full bg-primary transition-all duration-300"
            style={{ width: `${progress}%` }}
          />
        </div>
 
        {/* Header content */}
        <div className="flex items-center justify-between px-4 py-3">
          <div className="flex-1">
            <h1 className="line-clamp-1 text-sm font-medium text-foreground">
              {recipe.title}
            </h1>
            <p className="text-xs text-muted-foreground">
              Step {currentStep + 1} of {totalSteps}
            </p>
          </div>
 
          <button
            onClick={onExit}
            className="rounded-full bg-muted p-2 text-muted-foreground transition-colors hover:bg-muted/80"
            aria-label="Exit play mode"
          >
            <X className="h-5 w-5" />
          </button>
        </div>
      </div>
 
      {/* Main content area */}
      <div className="flex flex-1 flex-col">
        {/* Instruction display */}
        <div className="flex flex-1 items-center justify-center p-6">
          <div className="max-w-2xl text-center">
            {/* Step number */}
            <div className="mx-auto mb-6 flex h-12 w-12 items-center justify-center rounded-full bg-primary text-xl font-bold text-primary-foreground">
              {currentStep + 1}
            </div>
 
            {/* Instruction text */}
            <p className="text-xl leading-relaxed text-foreground sm:text-2xl">
              {currentInstruction}
            </p>
          </div>
        </div>
 
        {/* Navigation buttons */}
        <div className="flex items-center justify-between border-t border-border px-4 py-4">
          <button
            onClick={handlePrevious}
            disabled={currentStep === 0}
            className={cn(
              'flex items-center gap-2 rounded-lg px-4 py-3 text-sm font-medium transition-colors',
              currentStep === 0
                ? 'text-muted-foreground opacity-50'
                : 'bg-muted text-foreground hover:bg-muted/80'
            )}
          >
            <ChevronLeft className="h-5 w-5" />
            Previous
          </button>
 
          {/* Step indicators */}
          <div className="hidden gap-1.5 sm:flex">
            {instructions.map((_, idx) => (
              <button
                key={idx}
                onClick={() => setCurrentStep(idx)}
                className={cn(
                  'h-2 w-2 rounded-full transition-all',
                  idx === currentStep
                    ? 'w-6 bg-primary'
                    : idx < currentStep
                      ? 'bg-primary/50'
                      : 'bg-muted'
                )}
                aria-label={`Go to step ${idx + 1}`}
              />
            ))}
          </div>
 
          <button
            onClick={handleNext}
            disabled={currentStep === totalSteps - 1}
            className={cn(
              'flex items-center gap-2 rounded-lg px-4 py-3 text-sm font-medium transition-colors',
              currentStep === totalSteps - 1
                ? 'text-muted-foreground opacity-50'
                : 'bg-primary text-primary-foreground hover:bg-primary/90'
            )}
          >
            Next
            <ChevronRight className="h-5 w-5" />
          </button>
        </div>
 
        {/* Timer panel */}
        <TimerPanel timers={timers} instructionText={currentInstruction} aiAvailable={aiAvailable} />
      </div>
    </div>
  )
}
 
← Back to Dashboard