All files / web/src/components/practice SessionSongPlayer.tsx

0% Statements 0/233
0% Branches 0/1
0% Functions 0/1
0% Lines 0/233

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
'use client'

/**
 * Kid-friendly audio player for AI-generated session celebration songs.
 *
 * Delegates the "ready" state to <SyncedLyricsPlayer> — the integrated
 * lyrics + playback surface where the lyrics ARE the player (each word
 * is a seek target, active word highlights as it's sung).
 *
 * States:
 * - Generating: animated shimmer with "Creating your song..." text
 * - Ready: <SyncedLyricsPlayer variant="compact" />
 * - Failed: <SongFailureCard>
 * - Absent: renders nothing (don't show errors to kids)
 */

import { useEffect, useRef } from 'react'
import { useElapsedMs } from '@/hooks/useElapsedMs'
import { useSessionSong } from '@/hooks/useSessionSong'
import { ShareSongPopover } from '@/components/song/ShareSongPopover'
import { SyncedLyricsPlayer } from '@/components/song/SyncedLyricsPlayer'
import { SongFailureCard } from './SongFailureCard'
import { css } from '../../../styled-system/css'

interface SessionSongPlayerProps {
  playerId: string
  planId: string
  /** Whether to trigger a completion fallback POST if no song exists */
  triggerFallback?: boolean
}

const GENERATING_COPY: Record<string, string> = {
  pending: 'Getting ready to write your song...',
  prompt_generating: 'Listening to how your session went...',
  generating: 'Writing your celebration song 🎵',
}

function getGeneratingCopy(status: string | undefined): string {
  return (status && GENERATING_COPY[status]) || 'Creating your song...'
}

const LONG_GENERATION_MS = 45_000
const VERY_LONG_GENERATION_MS = 180_000
const LONG_GENERATION_COPY = "Still cooking — this one's taking a little longer, hang tight!"
const VERY_LONG_GENERATION_COPY = "You can come back later — we'll have it ready for you"

function getReassuranceCopy(status: string | undefined, elapsedMs: number | null): string {
  if (elapsedMs != null && elapsedMs >= VERY_LONG_GENERATION_MS) {
    return VERY_LONG_GENERATION_COPY
  }
  if (elapsedMs != null && elapsedMs >= LONG_GENERATION_MS) {
    return LONG_GENERATION_COPY
  }
  return getGeneratingCopy(status)
}

const CONNECTION_LOST_COPY =
  "Lost the live updates — your song is still cooking, but we won't see it the moment it's done."
const CONNECTION_LOST_OWNER_COPY =
  'Lost the realtime connection to the server. The song is still generating in the background — reconnect to resume live updates.'

export function SessionSongPlayer({
  playerId,
  planId,
  triggerFallback = false,
}: SessionSongPlayerProps) {
  const {
    song,
    isGenerating,
    isReady,
    failureKind,
    errorDetail,
    viewerIsOwner,
    connectionState,
    reconnect,
  } = useSessionSong({
    playerId,
    planId,
    enabled: true,
  })

  const elapsedMs = useElapsedMs(song?.createdAt ?? null)

  const fallbackTriggered = useRef(false)

  // Fire completion fallback trigger if needed
  useEffect(() => {
    if (triggerFallback && !song && !fallbackTriggered.current) {
      fallbackTriggered.current = true
      fetch(`/api/curriculum/${playerId}/sessions/plans/${planId}/song`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ triggerSource: 'completion_fallback' }),
      }).catch(() => {
        // Fire and forget
      })
    }
  }, [triggerFallback, song, playerId, planId])

  // Don't render anything if there's no song at all
  if (!song && !isGenerating) return null

  // Show a soft failure card instead of silently swallowing failures.
  // Kid sees a warm one-liner; account owners/admins also see remediation.
  if (song?.status === 'failed') {
    return (
      <SongFailureCard
        failureKind={failureKind}
        errorDetail={errorDetail}
        viewerIsOwner={viewerIsOwner}
      />
    )
  }

  return (
    <div
      data-component="session-song-player"
      className={css({
        mx: 'auto',
        maxW: '480px',
        mb: 4,
      })}
    >
      {isGenerating && !isReady && connectionState !== 'lost' && (
        <div
          className={css({
            display: 'flex',
            alignItems: 'center',
            gap: 3,
            p: 4,
            borderRadius: 'xl',
            bg: 'purple.50',
            _dark: { bg: 'purple.900/30' },
          })}
        >
          <div
            className={css({
              w: 8,
              h: 8,
              borderRadius: 'full',
              bg: 'purple.200',
              _dark: { bg: 'purple.700' },
              animation: 'pulse 1.5s ease-in-out infinite',
              flexShrink: 0,
            })}
          />
          <span
            className={css({
              fontSize: 'sm',
              color: 'purple.700',
              _dark: { color: 'purple.200' },
              fontWeight: 'medium',
            })}
          >
            {getReassuranceCopy(song?.status, elapsedMs)}
            {connectionState === 'reconnecting' && (
              <span
                className={css({
                  ml: 2,
                  fontSize: 'xs',
                  color: 'purple.500',
                  _dark: { color: 'purple.400' },
                  fontStyle: 'italic',
                })}
              >
                · reconnecting…
              </span>
            )}
          </span>
        </div>
      )}

      {isGenerating && !isReady && connectionState === 'lost' && (
        <div
          data-element="connection-lost"
          className={css({
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'start',
            gap: 2,
            p: 4,
            borderRadius: 'xl',
            bg: 'amber.50',
            border: '1px solid',
            borderColor: 'amber.200',
            _dark: { bg: 'amber.900/30', borderColor: 'amber.700' },
          })}
        >
          <span
            className={css({
              fontSize: 'sm',
              color: 'amber.800',
              _dark: { color: 'amber.100' },
              fontWeight: 'medium',
            })}
          >
            {viewerIsOwner ? CONNECTION_LOST_OWNER_COPY : CONNECTION_LOST_COPY}
          </span>
          <button
            type="button"
            data-action="reconnect-session-song"
            onClick={reconnect}
            className={css({
              fontSize: 'xs',
              fontWeight: 'bold',
              color: 'amber.900',
              _dark: { color: 'amber.100' },
              textDecoration: 'underline',
              cursor: 'pointer',
              border: 'none',
              bg: 'transparent',
              p: 0,
            })}
          >
            Reconnect
          </button>
        </div>
      )}

      {isReady && song?.audioPath && (
        <SyncedLyricsPlayer
          audioPath={song.audioPath}
          alignmentPath={song.alignmentPath}
          lyrics={song.lyrics ?? []}
          title={song.title}
          variant="compact"
          autoPlay
          footer={song.id ? <ShareSongPopover songId={song.id} songTitle={song.title} /> : null}
        />
      )}
    </div>
  )
}