import { useState } from 'react'
import { playSound, SFX_BUTTON_DEFAULT } from '../lib/sounds'
import { RecordingPlayer } from './RecordingPlayer'
import testRecording from '../data/test-recording.json'
import styles from './Tutorial.module.css'

const TUTORIAL_SEEN_KEY = 'tutorialSeen'

export function useTutorialSeen() {
  const [seen, setSeen] = useState(
    () => localStorage.getItem(TUTORIAL_SEEN_KEY) === 'true',
  )
  const markSeen = () => {
    localStorage.setItem(TUTORIAL_SEEN_KEY, 'true')
    setSeen(true)
  }
  return { seen, markSeen }
}

const TIPS = [
  'Exaggerate your steps — big, clear movements work best',
  'Bring your foot fully back to center after each step',
  'Place a hand on the opposite shoulder to pause; do it again to resume.',
  'Try to stay in one spot',
  'Face the camera with your body',
  "Stand so you're fully visible — your body should be above the red line, and keep your head in frame too",
]

export function Tutorial({ onDismiss }: { onDismiss: () => void }) {
  const [tipIndex, setTipIndex] = useState(0)
  const isLast = tipIndex >= TIPS.length - 1

  function handleNext() {
    playSound(SFX_BUTTON_DEFAULT)
    if (isLast) {
      onDismiss()
    } else {
      setTipIndex(i => i + 1)
    }
  }

  return (
    <div className={styles.overlay}>
      <div className={styles.card}>
        <h2 className={`${styles.title} font-title`}>TIPS</h2>

        {/* Desktop: player + all tips side by side */}
        <div className={styles.desktopBody}>
          <div className={styles.playerWrap}>
            <RecordingPlayer
              frames={testRecording}
              width={240}
              height={180}
              autoPlay
              loop
              showControls={false}
            />
          </div>
          <ol className={styles.tips}>
            {TIPS.map((tip, i) => <li key={i}>{tip}</li>)}
          </ol>
        </div>
        <button
          className={`${styles.dismissBtn} ${styles.desktopOnly} font-title`}
          onClick={() => {
            playSound(SFX_BUTTON_DEFAULT)
            onDismiss()
          }}
        >
          GOT IT
        </button>

        {/* Mobile: player + one tip at a time */}
        <div className={styles.mobileBody}>
          <div className={styles.playerWrap}>
            <RecordingPlayer
              frames={testRecording}
              width={240}
              height={180}
              autoPlay
              loop
              showControls={false}
            />
          </div>
          <div className={styles.stepperTip}>
            <span className={styles.stepperCount}>{tipIndex + 1}/{TIPS.length}</span>
            <p className={styles.stepperText}>{TIPS[tipIndex]}</p>
          </div>
          <button
            className={`${styles.dismissBtn} font-title`}
            onClick={handleNext}
          >
            {isLast ? 'GOT IT' : 'NEXT'}
          </button>
        </div>
      </div>
    </div>
  )
}
