// ============ DATA ============
const exerciseIcons = [
  { name: 'eye', color: '#667eea' }, { name: 'star', color: '#f59e0b' },
  { name: 'heart', color: '#ef4444' }, { name: 'flower-2', color: '#ec4899' },
  { name: 'cloud', color: '#06b6d4' }, { name: 'gem', color: '#8b5cf6' },
  { name: 'fish', color: '#14b8a6' }, { name: 'bird', color: '#f97316' },
  { name: 'leaf', color: '#22c55e' }, { name: 'mountain', color: '#6366f1' },
  { name: 'waves', color: '#0ea5e9' }, { name: 'shell', color: '#f472b6' },
  { name: 'feather', color: '#a78bfa' }, { name: 'flame', color: '#fb923c' },
  { name: 'snowflake', color: '#7dd3fc' }, { name: 'tree-pine', color: '#4ade80' },
  { name: 'anchor', color: '#64748b' }, { name: 'compass', color: '#fbbf24' },
  { name: 'diamond', color: '#c084fc' }, { name: 'crown', color: '#facc15' },
  { name: 'moon', color: '#a5b4fc' }, { name: 'sun', color: '#fcd34d' },
  { name: 'droplets', color: '#38bdf8' }, { name: 'zap', color: '#fde047' }
];

const positivityIcons = [
  { name: 'heart', color: '#f472b6' }, { name: 'star', color: '#fbbf24' },
  { name: 'sun', color: '#fb923c' }, { name: 'sparkles', color: '#f9a8d4' },
  { name: 'flower-2', color: '#f87171' }, { name: 'gem', color: '#c084fc' },
  { name: 'crown', color: '#fcd34d' }, { name: 'moon', color: '#d8b4fe' },
  { name: 'cloud', color: '#fda4af' }, { name: 'feather', color: '#fdba74' }
];

const encouragements = [
  "You're doing great. Just follow the movement.",
  "Let the memory stay distant. Focus on the icon.",
  "Breathe gently. You're safe here.",
  "Your mind is processing. Keep following.",
  "Every moment is progress. Stay with it.",
  "You're stronger than you know. Keep going.",
  "Let the tension release with each pass.",
  "Stay present. The past cannot hurt you now.",
  "You're rewiring your response. Well done.",
  "Almost there. You're doing wonderfully."
];

// Combined encouragements with affirmations for positivity mode
const positivityMessages = [
  "You are resilient. Let peace wash over you.",
  "You have the power to heal. Breathe gently.",
  "You are worthy of peace and happiness.",
  "Your strength is inspiring. Keep going.",
  "You deserve this moment of calm.",
  "Feel the warmth of self-compassion.",
  "You are safe. You are whole.",
  "Let gratitude fill your heart.",
  "This peace is yours to keep.",
  "You are transforming beautifully."
];

const defaultSettings = { baseSpeed: 3, flashDuration: 500, minDuration: 30, maxDuration: 180, durationPerPoint: 15, breathingSpeed: 6 };

// ============ ICON COMPONENT ============
const Icon = ({ name, size = 24, color = 'currentColor' }) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (ref.current && typeof lucide !== 'undefined') {
      ref.current.innerHTML = '';
      const pascalName = name.split('-').map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('');
      if (lucide.icons && lucide.icons[pascalName]) {
        const svg = lucide.createElement(lucide.icons[pascalName]);
        if (svg) { svg.setAttribute('width', size); svg.setAttribute('height', size); svg.setAttribute('stroke', color); ref.current.appendChild(svg); }
      }
    }
  }, [name, size, color]);
  return <span ref={ref} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }} />;
};

// ============ MAIN APP ============
const { useState, useEffect, useRef, useCallback } = React;

function SideToSideApp() {
  const [currentStep, setCurrentStep] = useState('welcome');
  const [displayedStep, setDisplayedStep] = useState('welcome');
  const [isVisible, setIsVisible] = useState(true);
  const [history, setHistory] = useState([]);
  const [disclaimerAccepted, setDisclaimerAccepted] = useState(false);
  const [showHowItWorks, setShowHowItWorks] = useState(false);
  const [showHowItWorks, setShowHowItWorks] = useState(false);
  const [showSafety, setShowSafety] = useState(false);
  const [triggerWords, setTriggerWords] = useState('');
  const [initialRating, setInitialRating] = useState(5);
  const [currentRating, setCurrentRating] = useState(null);
  const [sessionCount, setSessionCount] = useState(0);
  const [settings] = useState(defaultSettings);
  
  const [isExerciseRunning, setIsExerciseRunning] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [exerciseTime, setExerciseTime] = useState(0);
  const [totalExerciseTime, setTotalExerciseTime] = useState(60);
  const [currentEncouragement, setCurrentEncouragement] = useState(0);
  const [showFlashWord, setShowFlashWord] = useState(false);
  const [flashWordTop, setFlashWordTop] = useState(50);
  const [flashWordLeft, setFlashWordLeft] = useState(50);
  const [currentFlashWord, setCurrentFlashWord] = useState('');
  const [currentIconIndex, setCurrentIconIndex] = useState(0);
  const [iconChangeTime, setIconChangeTime] = useState(null);
  const [totalReactions, setTotalReactions] = useState(0);
  const [showReactionFeedback, setShowReactionFeedback] = useState(false);
  const [reactionFeedbackText, setReactionFeedbackText] = useState('');
  const [reactionFeedbackKey, setReactionFeedbackKey] = useState(0); // Unique key for animation
  const [hasRespondedToCurrentIcon, setHasRespondedToCurrentIcon] = useState(true);
  
  const [showLandscapePrompt, setShowLandscapePrompt] = useState(false); 
  const [showSessionCongrats, setShowSessionCongrats] = useState(false);
  
  const exerciseTimerRef = useRef(null);
  const flashTimerRef = useRef(null);
  const iconChangeTimerRef = useRef(null);
  const lastTapTimeRef = useRef(0); // Debounce ref to prevent double-firing on mobile
  const touchHandledRef = useRef(false); // Track if touch event handled to prevent click double-fire
  const hasRespondedRef = useRef(true); // Ref for immediate checking (avoids state batching issues)

  const isPositivityMode = displayedStep === 'positivity';
  const currentIcons = isPositivityMode ? positivityIcons : exerciseIcons;
  const currentMessages = isPositivityMode ? positivityMessages : encouragements;

  // Keep positivity particles stable across renders (avoids mobile jitter)
  const positivityParticles = React.useMemo(() => {
    return [...Array(15)].map((_, i) => ({
      id: i,
      hue: 300 + Math.random() * 60,
      left: Math.random() * 100,
      top: Math.random() * 100,
      delay: Math.random() * 2
    }));
  }, []);

  const calculateDuration = useCallback((rating) => Math.min(settings.minDuration + rating * settings.durationPerPoint, settings.maxDuration), [settings]);
  const formatTime = (s) => `${Math.floor(s/60)}:${(s%60).toString().padStart(2,'0')}`;
  
  // Smooth transition - fade out, change, fade in
  const transitionTo = useCallback((newStep, addToHistory = true) => {
    if (newStep === displayedStep) return;
    setIsVisible(false);
    setTimeout(() => {
      if (addToHistory && displayedStep !== 'exercise' && displayedStep !== 'positivity') {
        setHistory(p => [...p, displayedStep]);
      }
      setCurrentStep(newStep);
      setDisplayedStep(newStep);
      setTimeout(() => setIsVisible(true), 50);
    }, 250);
  }, [displayedStep]);
  
  const goToStep = (step) => transitionTo(step, true);
  
  const goBack = () => { 
    if (history.length > 0) {
      const prevStep = history[history.length - 1];
      setIsVisible(false);
      setTimeout(() => {
        setHistory(p => p.slice(0, -1));
        setCurrentStep(prevStep);
        setDisplayedStep(prevStep);
        setTimeout(() => setIsVisible(true), 50);
      }, 250);
    }
  };
  
  const resetApp = () => { 
    setIsVisible(false);
    setTimeout(() => {
      setCurrentStep('welcome'); 
      setDisplayedStep('welcome');
      setHistory([]); 
      setTriggerWords(''); 
      setInitialRating(5); 
      setCurrentRating(null); 
      setSessionCount(0); 
      setIsExerciseRunning(false); 
      setIsPaused(false); 
      setExerciseTime(0); 
      setTotalReactions(0); 
      setShowSessionCongrats(false);
      setTimeout(() => setIsVisible(true), 50);
    }, 250);
  };
  
  const startExercise = (duration) => { 
    setTotalExerciseTime(duration || calculateDuration(currentRating || initialRating)); 
    setExerciseTime(0); 
    setIsExerciseRunning(true); 
    setIsPaused(false); 
    setCurrentEncouragement(0); 
    setCurrentIconIndex(0); 
    setTotalReactions(0); 
    setHasRespondedToCurrentIcon(true);
    hasRespondedRef.current = true; // Start with responded=true until first icon change
    setShowReactionFeedback(false);
    setShowSessionCongrats(false);
  };
  
  const togglePause = () => setIsPaused(!isPaused);
  
  const stopExercise = useCallback(() => { 
    setIsExerciseRunning(false); 
    setIsPaused(false); 
    setShowReactionFeedback(false); 
    if (exerciseTimerRef.current) clearInterval(exerciseTimerRef.current); 
    if (flashTimerRef.current) clearTimeout(flashTimerRef.current); 
    if (iconChangeTimerRef.current) clearTimeout(iconChangeTimerRef.current);
  }, []);
  
  const changeIcon = useCallback(() => { 
    if (!isExerciseRunning || isPaused) return; 
    const icons = isPositivityMode ? positivityIcons : exerciseIcons;
    let n; 
    do { n = Math.floor(Math.random() * icons.length); } while (n === currentIconIndex && icons.length > 1); 
    setCurrentIconIndex(n); 
    setIconChangeTime(performance.now()); 
    setHasRespondedToCurrentIcon(false);
    hasRespondedRef.current = false; // Reset ref immediately
    iconChangeTimerRef.current = setTimeout(changeIcon, 2000 + Math.random() * 3000); 
  }, [isExerciseRunning, isPaused, currentIconIndex, isPositivityMode]);
  
  // Handle tap/reaction with debouncing to prevent double-firing on mobile
  const handleReaction = useCallback(() => { 
    // First check: use ref for immediate response (avoids React state batching delays)
    if (hasRespondedRef.current) return;
    
    // Second check: debounce within 300ms
    const now = performance.now();
    if (now - lastTapTimeRef.current < 300) return;
    lastTapTimeRef.current = now;
    
    if (!isExerciseRunning || isPaused) return; 
    
    // Mark as responded IMMEDIATELY via ref (before any state updates)
    hasRespondedRef.current = true;
    
    // Calculate score based on reaction time
    let s = Math.round(100 - ((performance.now() - iconChangeTime - 150) / 1050) * 100); 
    s = Math.max(0, Math.min(100, s)); 
    
    // Batch all state updates together
    setTotalReactions(p => p + 1); 
    setReactionFeedbackText(s.toString()); 
    setReactionFeedbackKey(k => k + 1);
    setShowReactionFeedback(true); 
    setHasRespondedToCurrentIcon(true); 
  }, [isExerciseRunning, isPaused, iconChangeTime]);

  
  // Mobile viewport height fix (prevents iOS address-bar jumpiness)
  useEffect(() => {
    const setVh = () => {
      const vh = window.innerHeight * 0.01;
      document.documentElement.style.setProperty('--vh', `${vh}px`);
    };
    setVh();
    window.addEventListener('resize', setVh);
    window.addEventListener('orientationchange', setVh);
    return () => {
      window.removeEventListener('resize', setVh);
      window.removeEventListener('orientationchange', setVh);
    };
  }, []);

  // Orientation prompt + wake lock (no fullscreen)
  useEffect(() => {
    let wl = null;

    // Only request wake lock during active exercise
    if ((displayedStep === 'exercise' || displayedStep === 'positivity') && 'wakeLock' in navigator) {
      navigator.wakeLock.request('screen').then(l => { wl = l; }).catch(() => {});
    }

    const check = () => {
      const mob = window.innerWidth < 768 || window.innerHeight < 768;
      const port = window.innerHeight > window.innerWidth;

      // Only show prompts during active exercise screens
      if ((displayedStep === 'exercise' || displayedStep === 'positivity') && mob) {
        setShowLandscapePrompt(port);
      } else {
        setShowLandscapePrompt(false);
      }
    };

    check();
    window.addEventListener('resize', check);

    return () => {
      window.removeEventListener('resize', check);
      if (wl) wl.release().catch(() => {});
    };
  }, [displayedStep]);


  // Keyboard
  useEffect(() => { 
    if ((displayedStep !== 'exercise' && displayedStep !== 'positivity') || !isExerciseRunning) return; 
    const h = (e) => { if (e.code === 'Space') { e.preventDefault(); handleReaction(); } }; 
    window.addEventListener('keydown', h); 
    return () => window.removeEventListener('keydown', h); 
  }, [displayedStep, isExerciseRunning, handleReaction]);

  // Main timer
  useEffect(() => { 
    if (!isExerciseRunning || isPaused) return; 
    
    const messages = isPositivityMode ? positivityMessages : encouragements;
    
    exerciseTimerRef.current = setInterval(() => { 
      setExerciseTime(p => { 
        const n = p + 1; 
        const idx = Math.min(Math.floor(n / Math.max(1, Math.floor(totalExerciseTime / messages.length))), messages.length - 1);
        if (idx !== currentEncouragement) setCurrentEncouragement(idx); 
        if (n >= totalExerciseTime) { 
          stopExercise(); 
          if (!isPositivityMode) setSessionCount(x => x + 1);
          setShowSessionCongrats(true);
        } 
        return n; 
      }); 
    }, 1000); 
    
    iconChangeTimerRef.current = setTimeout(changeIcon, 1500 + Math.random() * 1500); 
    
    return () => { 
      if (exerciseTimerRef.current) clearInterval(exerciseTimerRef.current); 
      if (iconChangeTimerRef.current) clearTimeout(iconChangeTimerRef.current);
    }; 
  }, [isExerciseRunning, isPaused, totalExerciseTime, changeIcon, stopExercise, currentEncouragement, isPositivityMode]);

  // Flash words (main exercise only)
  useEffect(() => { 
    if (!isExerciseRunning || isPaused || isPositivityMode) { 
      if (flashTimerRef.current) { clearTimeout(flashTimerRef.current); flashTimerRef.current = null; } 
      return; 
    } 
    const wl = triggerWords.split(',').map(w => w.trim()).filter(w => w.length > 0); 
    if (wl.length === 0) return; 
    const base = (totalExerciseTime * 1000) / 7; 
    const flash = () => { 
      setFlashWordTop(10 + Math.random() * 80); 
      setFlashWordLeft(10 + Math.random() * 80); 
      setCurrentFlashWord(wl[Math.floor(Math.random() * wl.length)]); 
      setShowFlashWord(true); 
      setTimeout(() => setShowFlashWord(false), settings.flashDuration); 
      flashTimerRef.current = setTimeout(flash, base * (0.7 + Math.random() * 0.6)); 
    }; 
    flashTimerRef.current = setTimeout(flash, base * (0.4 + Math.random() * 0.2)); 
    return () => { if (flashTimerRef.current) { clearTimeout(flashTimerRef.current); flashTimerRef.current = null; } }; 
  }, [isExerciseRunning, isPaused, triggerWords, totalExerciseTime, settings.flashDuration, isPositivityMode]);

  // Reaction feedback
  useEffect(() => { 
    if (showReactionFeedback) { 
      const t = setTimeout(() => setShowReactionFeedback(false), 600); 
      return () => clearTimeout(t); 
    } 
  }, [showReactionFeedback]);

  const currentIconData = currentIcons[currentIconIndex] || currentIcons[0];

  // ============ RENDER ============
  
  const renderWelcome = () => (
    <div className="card welcome-card">
      <div className="text-center mb-6">
        <div className="logo-container"><Icon name="eye" size={40} color="white" /></div>
        <h1 className="title">Side to Side</h1>
        <p className="subtitle">Personal Edition</p>
      </div>
      <div className="intro-text mb-4"><p>This app guides you through a gentle side-to-side calming practice: brief taps of a difficult memory while your eyes follow slow, steady movement.</p></div>
      <div className="expandable-section">
        <button className="expandable-header" onClick={() => setShowHowItWorks(!showHowItWorks)}>
          <div className="expandable-title"><Icon name="book-open" size={20} /><span>How does it work?</span></div>
          <Icon name={showHowItWorks ? "chevron-up" : "chevron-down"} size={20} />
        </button>
        {showHowItWorks && <div className="expandable-content"><p>Slow side-to-side eye movement while you lightly touch on a difficult thought can help the feeling soften. It is a calming practice, not therapy — if something feels too big, talk to someone qualified.</p></div>}
      </div>
      <div className="expandable-section">
        <button className="expandable-header" onClick={() => setShowHowItWorks(!showHowItWorks)}>
          <div className="expandable-title"><Icon name="sparkles" size={20} /><span>How This App Works</span></div>
          <Icon name={showHowItWorks ? "chevron-up" : "chevron-down"} size={20} />
        </button>
        {showHowItWorks && <div className="expandable-content"><ul className="feature-list"><li>Your trigger words flash briefly</li><li>The moving ball provides bilateral stimulation</li><li>Changing icons keep your mind engaged</li></ul></div>}
      </div>
      <div className="expandable-section">
        <button className="expandable-header" onClick={() => setShowSafety(!showSafety)}>
          <div className="expandable-title"><Icon name="shield" size={20} /><span>Safety Information</span></div>
          <Icon name={showSafety ? "chevron-up" : "chevron-down"} size={20} />
        </button>
        {showSafety && <div className="expandable-content"><ul className="feature-list"><li>For severe trauma, work with a therapist</li><li>You can pause or end any session</li></ul></div>}
      </div>
      <div className="disclaimer-box">
        <div className="disclaimer-header"><Icon name="alert-triangle" size={20} color="#fbbf24" /><h3>Important Disclaimer</h3></div>
        <ul className="disclaimer-list"><li>Not a substitute for professional treatment</li><li>By continuing, you accept responsibility</li></ul>
        <label className="disclaimer-checkbox"><input type="checkbox" checked={disclaimerAccepted} onChange={(e) => setDisclaimerAccepted(e.target.checked)} /><span>I understand and accept these terms</span></label>
      </div>
      <button className={`btn-primary full-width ${!disclaimerAccepted ? 'disabled' : ''}`} onClick={() => disclaimerAccepted && goToStep('memory-prep')} disabled={!disclaimerAccepted}>Begin <Icon name="chevron-right" size={20} /></button>
      <a className="kids-mode-link" href="index.html"><Icon name="home" size={16} /> Switch experience</a>
    </div>
  );

  const renderMemoryPrep = () => (
    <div className="card">
      <button onClick={goBack} className="btn-back"><Icon name="arrow-left" size={16} /> Back</button>
      <h2 className="section-title">Prepare Your Memory</h2>
      <div className="step-box"><div className="step-number">1</div><div className="step-content"><h3>Think of a Positive Resource</h3><p>Bring to mind a calm, safe, or happy memory.</p></div></div>
      <div className="step-box"><div className="step-number">2</div><div className="step-content"><h3>Identify Your Target Memory</h3><p>Think of the difficult memory briefly. Don't dwell on it.</p></div></div>
      <button className="btn-primary full-width" onClick={() => goToStep('trigger-words')}>I'm Ready <Icon name="chevron-right" size={20} /></button>
    </div>
  );

  const renderTriggerWords = () => (
    <div className="card">
      <button onClick={goBack} className="btn-back"><Icon name="arrow-left" size={16} /> Back</button>
      <h2 className="section-title">Trigger Words</h2>
      <p className="section-subtitle">Enter words that represent your memory. These will flash briefly.</p>
      <div className="input-container">
        <input type="text" placeholder="e.g., blue car" value={triggerWords} onChange={(e) => setTriggerWords(e.target.value)} className="text-input" />
        <p className="input-hint">Only you will see these words.</p>
      </div>
      <button className={`btn-primary full-width ${triggerWords.trim().length === 0 ? 'disabled' : ''}`} onClick={() => triggerWords.trim().length > 0 && goToStep('initial-rating')} disabled={triggerWords.trim().length === 0}>Continue <Icon name="chevron-right" size={20} /></button>
    </div>
  );

  const renderInitialRating = () => (
    <div className="card">
      <button onClick={goBack} className="btn-back"><Icon name="arrow-left" size={16} /> Back</button>
      <h2 className="section-title">Rate Your Disturbance</h2>
      <p className="section-subtitle">How disturbing would this memory feel right now?</p>
      <div className="rating-display">{initialRating}</div>
      <div className="slider-container">
        <input type="range" min="0" max="10" value={initialRating} onChange={(e) => setInitialRating(parseInt(e.target.value))} className="range-input large" />
        <div className="range-labels"><span>0 - None</span><span>10 - Worst</span></div>
      </div>
      <div className="duration-preview"><p>Duration: <strong>{formatTime(calculateDuration(initialRating))}</strong></p></div>
      <button className="btn-primary full-width" onClick={() => { setCurrentRating(initialRating); goToStep('pre-exercise'); }}>Ready <Icon name="chevron-right" size={20} /></button>
    </div>
  );

  const renderPreExercise = () => (
    <div className="card">
      <button onClick={goBack} className="btn-back"><Icon name="arrow-left" size={16} /> Back</button>
      <h2 className="section-title center"><Icon name="sparkles" size={24} color="#667eea" /> Ready to Start</h2>
      <div className="instructions-box">
        <h3>During the exercise:</h3>
        <ul className="instructions-list">
          <li>🎯 Follow the moving icon with your eyes</li>
          <li>⌨️ Press SPACE or tap when icon changes</li>
          <li>✨ Your words will flash briefly</li>
        </ul>
      </div>
      <div className="duration-display"><p className="text-sm text-muted">Duration</p><p className="duration-time">{formatTime(calculateDuration(currentRating || initialRating))}</p></div>
      <button className="btn-primary full-width large" onClick={() => { 
        setCurrentStep('exercise');
        setDisplayedStep('exercise');
        setTimeout(() => startExercise(), 300); 
      }}><Icon name="play" size={24} /> Start</button>
    </div>
  );

  const renderExerciseScreen = () => {
    const isPositivity = displayedStep === 'positivity';
    const containerClass = isPositivity ? 'exercise-container positivity-mode' : 'exercise-container';
    const ballColor = isPositivity ? 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)' : currentIconData.color;
    const ballShadow = '0 6px 16px rgba(0, 0, 0, 0.25)';

    const blockingOverlay = showLandscapePrompt || showSessionCongrats || isPaused;
    
    // Handle touch start - for mobile devices
    const handleTouchStart = (e) => {
      if (blockingOverlay) return;
      e.preventDefault(); // Prevent subsequent click event
      touchHandledRef.current = true;
      handleReaction();
      // Reset flag after a short delay (click events fire ~300ms after touch on some devices)
      setTimeout(() => { touchHandledRef.current = false; }, 400);
    };
    
    // Handle click - for desktop/mouse, but skip if touch already handled
    const handleClick = (e) => {
      if (blockingOverlay) return;
      if (touchHandledRef.current) return; // Skip if touch already handled this
      handleReaction();
    };
    
    return (
      <div
        className={containerClass}
        onClick={handleClick}
        onTouchStart={handleTouchStart}
      >
        {showLandscapePrompt && !showSessionCongrats && (
          <div
            className="landscape-prompt"
            onClick={(e) => e.stopPropagation()}
            onTouchStart={(e) => e.stopPropagation()}
          >
            <div className="landscape-prompt-content">
              <div className="phone-icon">📱</div>
              <div className="rotate-arrow">↻</div>
              <h3>Please Rotate Your Device</h3>
              <p>Turn to landscape mode</p>
            </div>
          </div>
        )} 
{showSessionCongrats ? (
          <div className={`session-congrats-overlay ${isVisible ? 'visible' : 'hidden'}`}>
            <div className="session-congrats-content">
              <div className="congrats-emojis">
                <span className="congrats-emoji bounce-1">{isPositivity ? '💜' : '🎉'}</span>
                <span className="congrats-emoji bounce-2">✨</span>
                <span className="congrats-emoji bounce-3">{isPositivity ? '🙏' : '🌟'}</span>
              </div>
              <h1 className="congrats-title">{isPositivity ? 'Beautiful Work!' : 'Amazing Work!'}</h1>
              <p className="congrats-subtitle">
                {isPositivity ? "You've completed your positivity session" : `You've completed session ${sessionCount}`}
              </p>
              <div className="congrats-message">
                <p>{isPositivity 
                  ? "Take a moment to appreciate the peace you've cultivated."
                  : "Your mind has done important processing work. Take a moment to acknowledge your courage."}
                </p>
              </div>
              <div className="congrats-emojis-bottom">
                <span>{isPositivity ? '🌸' : '💪'}</span>
                <span>❤️</span>
                <span>{isPositivity ? '☀️' : '🧠'}</span>
              </div>
              <button className="btn-primary large" onClick={() => { 
                // Transition first, then hide congrats after we've left this screen
                const nextStep = isPositivity ? 'complete' : 'post-rating';
                setIsVisible(false);
                setTimeout(() => {
                  setCurrentStep(nextStep);
                  setDisplayedStep(nextStep);
                  setShowSessionCongrats(false);
                  setTimeout(() => setIsVisible(true), 50);
                }, 250);
              }}>
                Next <Icon name="chevron-right" size={20} />
              </button>
            </div>
          </div>
        ) : (
          <>
            {isPositivity && (
              <div className="particles">
                {positivityParticles.map(p => (
                  <div key={p.id} className="particle" style={{
                    background: `hsl(${p.hue}, 70%, 70%)`,
                    left: `${p.left}%`,
                    top: `${p.top}%`,
                    animationDelay: `${p.delay}s`
                  }} />
                ))}
            </div>
            )}
            
            <div className="exercise-header">
              <div className="timer-box">
                <span className="timer-text">{formatTime(totalExerciseTime - exerciseTime)}</span>
              </div>
              <div className="reaction-counter">
                <span>{totalReactions} taps</span>
              </div>
              <div className="exercise-controls">
                <button onClick={(e) => { e.stopPropagation(); togglePause(); }} className="control-btn">
                  <Icon name={isPaused ? "play" : "pause"} size={20} />
                </button>
                <button onClick={(e) => { 
                  e.stopPropagation(); 
                  stopExercise(); 
                  if (!isPositivity) setSessionCount(p => p + 1);
                  setShowSessionCongrats(true);
                }} className="control-btn end">End</button>
              </div>
            </div>
            
            <div className="progress-bar">
              <div className={`progress-fill ${isPositivity ? 'positivity' : ''}`} style={{ width: `${(exerciseTime / totalExerciseTime) * 100}%` }} />
            </div>
            
            <div className="exercise-eye-level">
              {/* Score feedback - fixed height placeholder to prevent layout shift */}
              <div className="score-container">
                {showReactionFeedback && (
                  <div key={reactionFeedbackKey} className="reaction-feedback-inline">
                    {reactionFeedbackText}
                  </div>
                )}
              </div>
              
              <div className="encouragement-eye-level">
                <p>{currentMessages[currentEncouragement]}</p>
              </div>
              <div className="track-line">
                <div className={`ball-wrapper ${isPaused ? 'paused' : ''}`} style={{ animationDuration: `${settings.baseSpeed}s` }}>
                  <div className="ball" style={{ background: ballColor, boxShadow: ballShadow }}>
                    <Icon name={currentIconData.name} size={40} color="white" />
                  </div>
                </div>
              </div>
            </div>
            
            <div className="tap-instruction">
              <p>Tap or press SPACE when icon changes</p>
            </div>
            
            {!isPositivity && showFlashWord && currentFlashWord && (
              <div style={{
                position: 'absolute',
                top: `${flashWordTop}%`,
                left: `${flashWordLeft}%`,
                transform: 'translate(-50%,-50%)',
                fontSize: '24px',
                fontWeight: '700',
                color: 'rgba(255,255,255,0.92)',
                zIndex: 15,
                pointerEvents: 'none',
                textShadow: '0 2px 8px rgba(0,0,0,0.45)',
                whiteSpace: 'nowrap',
                animation: 'flashIn 0.2s ease-out'
              }}>{currentFlashWord}</div>
            )}
            
            {isPositivity && (
              <div className="breathing-guide">
                <div className="breathing-circle" style={{ animationDuration: `${settings.breathingSpeed}s` }}></div>
                <p className="breathing-text">Breathe</p>
              </div>
            )}
            
            {isPaused && (
              <div className="paused-overlay" onClick={(e) => e.stopPropagation()}>
                <div className="paused-content">
                  <Icon name="pause" size={60} color="rgba(255,255,255,0.7)" />
                  <p className="paused-text">Paused</p>
                  <button onClick={togglePause} className="btn-primary"><Icon name="play" size={20} /> Resume</button>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    );
  };

  const renderPostRating = () => (
    <div className="card">
      <div className="text-center mb-6">
        <div className="complete-icon"><Icon name="heart" size={28} color="white" /></div>
        <h2 className="section-title">Session {sessionCount} Complete</h2>
        <p className="text-muted">Let's check in.</p>
      </div>
      <p className="text-center mb-5">How disturbing does this memory feel now?</p>
      <div className="rating-display">{currentRating}</div>
      <div className="slider-container">
        <input type="range" min="0" max="10" value={currentRating} onChange={(e) => setCurrentRating(parseInt(e.target.value))} className="range-input large" />
        <div className="range-labels"><span>0 - None</span><span>10 - Worst</span></div>
      </div>
      <div className="progress-comparison">
        <p>Started at <strong>{initialRating}</strong> → Now <strong className={currentRating < initialRating ? 'positive' : ''}>{currentRating}</strong></p>
        {currentRating < initialRating && <p className="progress-message">✓ Reduced by {initialRating - currentRating} points!</p>}
      </div>
      <div className="button-group">
        {currentRating <= 1 ? (
          <button className="btn-primary full-width" onClick={() => { 
            setCurrentStep('positivity');
            setDisplayedStep('positivity');
            setTimeout(() => startExercise(30), 300); 
          }}><Icon name="sparkles" size={20} /> Celebrate</button>
        ) : currentRating >= 5 ? (
          <>
            <button className="btn-primary" onClick={() => goToStep('pre-exercise')}><Icon name="rotate-ccw" size={20} /> Another Round</button>
            <button className="btn-secondary" onClick={() => goToStep('complete')}>Finish</button>
          </>
        ) : (
          <>
            <button className="btn-primary" onClick={() => goToStep('pre-exercise')}><Icon name="rotate-ccw" size={20} /> Continue</button>
            <button className="btn-secondary" onClick={() => { 
              setCurrentStep('positivity');
              setDisplayedStep('positivity');
              setTimeout(() => startExercise(30), 300); 
            }}><Icon name="sparkles" size={20} /> Finish Well</button>
          </>
        )}
      </div>
    </div>
  );

  const renderComplete = () => (
    <div className="card">
      <div className="text-center">
        <div className="success-icon"><Icon name="sparkles" size={50} color="white" /></div>
        <h1 className="success-title">Well Done!</h1>
        <p className="success-subtitle">
          You've completed {sessionCount} session{sessionCount !== 1 ? 's' : ''}.
          {currentRating !== null && initialRating > currentRating && <> Disturbance: {initialRating} → {currentRating}</>}
        </p>
        <div className="positivity-options">
          <h3 className="positivity-options-title"><Icon name="sparkles" size={18} /> Positive reinforcement?</h3>
          <div className="positivity-buttons">
            <button className="btn-positivity" onClick={() => { 
              setCurrentStep('positivity');
              setDisplayedStep('positivity');
              setTimeout(() => startExercise(15), 300); 
            }}><Icon name="sun" size={20} /><span>Quick</span><span className="duration-badge">15s</span></button>
            <button className="btn-positivity" onClick={() => { 
              setCurrentStep('positivity');
              setDisplayedStep('positivity');
              setTimeout(() => startExercise(30), 300); 
            }}><Icon name="heart" size={20} /><span>Full</span><span className="duration-badge">30s</span></button>
          </div>
        </div>
        <div className="divider"><span>or</span></div>
        <div className="self-care-box">
          <h3>💚 Self-Care</h3>
          <ul><li>Drink water and ground yourself</li><li>Notice how your body feels</li></ul>
        </div>
        <button className="btn-primary" onClick={resetApp}><Icon name="rotate-ccw" size={20} /> New Session</button>
      </div>
    </div>
  );

  const renderScreen = () => {
    switch (displayedStep) {
      case 'welcome': return renderWelcome();
      case 'memory-prep': return renderMemoryPrep();
      case 'trigger-words': return renderTriggerWords();
      case 'initial-rating': return renderInitialRating();
      case 'pre-exercise': return renderPreExercise();
      case 'exercise': return renderExerciseScreen();
      case 'post-rating': return renderPostRating();
      case 'positivity': return renderExerciseScreen();
      case 'complete': return renderComplete();
      default: return renderWelcome();
    }
  };

  // Exercise and post-rating screens use fullscreen container
  if (displayedStep === 'exercise' || displayedStep === 'positivity') {
    return renderScreen();
  }
  
  // Post-rating stays in fullscreen-friendly dark container
  if (displayedStep === 'post-rating') {
    return (
      <div className="fullscreen-container">
        <div className={`screen-wrapper ${isVisible ? 'visible' : 'hidden'}`}>
          {renderScreen()}
        </div>
      </div>
    );
  }

  return (
    <div className="app-container">
      <div className={`screen-wrapper ${isVisible ? 'visible' : 'hidden'}`}>
        {renderScreen()}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<SideToSideApp />);