const { useState, useEffect, useRef } = React;

// 1. Interactive Breathing Ball Component
function BreathingBall({ isPlaying, inhaleTime = 4, holdTime = 4, exhaleTime = 4, holdTime2 = 4, soundscapeActive = false }) {
  const [phase, setPhase] = useState('inhale'); // inhale, hold, exhale, hold2
  const [secondsLeft, setSecondsLeft] = useState(inhaleTime);
  const timerRef = useRef(null);

  useEffect(() => {
    if (!isPlaying) {
      setPhase('inhale');
      setSecondsLeft(inhaleTime);
      if (timerRef.current) clearInterval(timerRef.current);
      return;
    }

    const startPhaseTimer = (currentPhase, duration) => {
      setPhase(currentPhase);
      setSecondsLeft(duration);
      
      let seconds = duration;
      if (timerRef.current) clearInterval(timerRef.current);
      
      timerRef.current = setInterval(() => {
        seconds -= 1;
        if (seconds <= 0) {
          clearInterval(timerRef.current);
          // Transition to next phase
          if (currentPhase === 'inhale') {
            startPhaseTimer('hold', holdTime);
          } else if (currentPhase === 'hold') {
            startPhaseTimer('exhale', exhaleTime);
          } else if (currentPhase === 'exhale') {
            startPhaseTimer('hold2', holdTime2);
          } else {
            startPhaseTimer('inhale', inhaleTime);
          }
        } else {
          setSecondsLeft(seconds);
        }
      }, 1000);
    };

    startPhaseTimer('inhale', inhaleTime);

    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [isPlaying, inhaleTime, holdTime, exhaleTime, holdTime2]);

  const getPhaseText = () => {
    if (!isPlaying) return '点击开始呼吸训练';
    switch (phase) {
      case 'inhale': return '吸气 (Inhale)';
      case 'hold': return '屏气 (Hold)';
      case 'exhale': return '呼气 (Exhale)';
      case 'hold2': return '屏气 (Hold)';
      default: return '';
    }
  };

  const getPhaseClass = () => {
    if (!isPlaying) return 'phase-exhale'; // Contracted state by default
    switch (phase) {
      case 'inhale': return 'phase-inhale';
      case 'hold':
      case 'hold2':
        return 'phase-hold';
      case 'exhale': return 'phase-exhale';
      default: return 'phase-exhale';
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
      <div className={`breath-circle-container ${getPhaseClass()}`}>
        <div className="breath-outer-wave"></div>
        <div className="breath-mid-wave"></div>
        <div className="breath-core">
          <span>{isPlaying ? secondsLeft : '静'}</span>
        </div>
      </div>
      <div className="breath-instruction">{getPhaseText()}</div>
      <div className="breath-timer">
        {isPlaying ? `循环中 · 阶段时长 ${secondsLeft} 秒` : '跟随呼吸球的大小变化调整气息'}
      </div>
    </div>
  );
}

// 2. Interactive Audio Player Component
function AudioPlayer({ themeTitle, themeSubtitle, isPlaying, onTogglePlay }) {
  const [progress, setProgress] = useState(0);
  const [duration] = useState(480); // 8 minutes = 480 seconds
  const [currentTime, setCurrentTime] = useState(0);
  const intervalRef = useRef(null);

  useEffect(() => {
    if (isPlaying) {
      intervalRef.current = setInterval(() => {
        setCurrentTime((prev) => {
          if (prev >= duration) {
            clearInterval(intervalRef.current);
            onTogglePlay(false);
            return 0;
          }
          const nextTime = prev + 1;
          setProgress((nextTime / duration) * 100);
          return nextTime;
        });
      }, 1000);
    } else {
      if (intervalRef.current) clearInterval(intervalRef.current);
    }
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [isPlaying, duration]);

  const formatTime = (secs) => {
    const m = Math.floor(secs / 60);
    const s = secs % 60;
    return `${m}:${s < 10 ? '0' : ''}${s}`;
  };

  const handleProgressBarClick = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const clickX = e.clientX - rect.left;
    const newProgress = (clickX / rect.width) * 100;
    setProgress(newProgress);
    setCurrentTime(Math.floor((newProgress / 100) * duration));
  };

  const renderVisualizer = () => {
    const bars = Array.from({ length: 12 });
    return (
      <div className="visual-wave-visualizer" style={{ marginLeft: 24 }}>
        {bars.map((_, i) => (
          <div
            key={i}
            className={`visual-wave-bar ${isPlaying ? 'animating' : ''}`}
            style={{
              height: isPlaying ? undefined : '3px',
              animationDuration: isPlaying ? `${0.5 + Math.random() * 0.6}s` : undefined
            }}
          />
        ))}
      </div>
    );
  };

  return (
    <div style={{ width: '100%' }}>
      <div className="audio-controls">
        <button className="play-btn" onClick={onTogglePlay}>
          {isPlaying ? (
            <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
              <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
            </svg>
          ) : (
            <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor" style={{ marginLeft: 3 }}>
              <path d="M8 5v14l11-7z"/>
            </svg>
          )}
        </button>
        <div>
          <div style={{ fontSize: 13, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-tertiary)' }}>
            今日推荐冥想
          </div>
          <h3 style={{ fontSize: 24, margin: '2px 0 4px 0', fontFamily: 'var(--font-serif)' }}>{themeTitle}</h3>
          <div style={{ fontSize: 14, color: 'var(--text-secondary)' }}>{themeSubtitle}</div>
        </div>
        {renderVisualizer()}
      </div>
      
      <div className="audio-player-progress-container">
        <span className="audio-time-label">{formatTime(currentTime)}</span>
        <div className="audio-progress-bar-bg" onClick={handleProgressBarClick}>
          <div className="audio-progress-bar-fill" style={{ width: `${progress}%` }}></div>
        </div>
        <span className="audio-time-label">{formatTime(duration)}</span>
      </div>
    </div>
  );
}

// 3. Mood Slider Component
function MoodSlider({ value, onChange }) {
  const getMoodConfig = (val) => {
    if (val < 25) return { emoji: '😞', label: '焦虑起伏', color: '#8e9e95', quote: '“杂念丛生亦是自然，允许自己以现有的状态存在。”' };
    if (val < 50) return { emoji: '😐', label: '心绪微动', color: '#97a89c', quote: '“如水般接纳，不去评判好坏，呼吸是你的锚点。”' };
    if (val < 75) return { emoji: '🙂', label: '心平气和', color: '#7c8e7e', quote: '“感受身体的放松，觉知此刻内心的温润与安定。”' };
    return { emoji: '😌', label: '物我两忘', color: '#5d6d5d', quote: '“如水波平息，静夜安详，心灵在此刻回归深邃。”' };
  };

  const { emoji, label, color, quote } = getMoodConfig(value);

  return (
    <div className="mood-slider-container">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 14, fontWeight: 500 }}>今日心境觉知</span>
        <span style={{ fontSize: 13, color: color, fontWeight: 600 }}>{label}</span>
      </div>
      
      <input
        type="range"
        min="1"
        max="100"
        value={value}
        onChange={(e) => onChange(parseInt(e.target.value))}
        className="mood-slider"
        style={{ '--accent': color }}
      />
      
      <div className="mood-labels">
        <span>焦虑/浮躁</span>
        <span>平静/悠然</span>
      </div>
      
      <div className="mood-status-display">
        <span className="mood-face">{emoji}</span>
      </div>
      
      <div className="mood-quote">{quote}</div>
    </div>
  );
}

// 4. White Noise / Soundscapes Component
function Soundscapes({ selectedSounds, onToggleSound, volumes = {}, onVolumeChange, customSounds = [], onDeleteCustomSound }) {
  const defaultSounds = [
    { id: 'rain', icon: '🌧️', title: '山林细雨', volume: '15% Volume' },
    { id: 'fire', icon: '🔥', title: '暖冬木柴', volume: '30% Volume' },
    { id: 'wave', icon: '🌊', title: '深海潮汐', volume: '20% Volume' },
    { id: 'wind', icon: '🍃', title: '松涛山风', volume: '10% Volume' },
  ];

  const allSounds = [
    ...defaultSounds,
    ...customSounds.map(s => ({
      id: s.id,
      icon: '🎵',
      title: s.name,
      volume: '自定义音轨',
      isCustom: true
    }))
  ];

  return (
    <div style={{ width: '100%' }}>
      <h3 style={{ fontSize: 18, marginBottom: 16, fontFamily: 'var(--font-serif)' }}>环境伴奏（环境白噪音）</h3>
      <div className="sounds-grid" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', display: 'grid', gap: 16 }}>
        {allSounds.map((sound) => {
          const isActive = selectedSounds.includes(sound.id);
          const vol = volumes[sound.id] || 30;
          return (
            <div key={sound.id} style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <div
                className={`sound-card ${isActive ? 'active' : ''}`}
                onClick={() => onToggleSound(sound.id)}
                style={{ position: 'relative' }}
              >
                <span className="sound-icon">{sound.icon}</span>
                <div className="sound-info" style={{ marginRight: sound.isCustom ? 24 : 0 }}>
                  <span className="sound-title" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'block', maxWidth: 140 }}>
                    {sound.title}
                  </span>
                  <span className="sound-volume">{isActive ? '伴奏已开启' : sound.volume}</span>
                </div>
                
                {sound.isCustom && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      if (onDeleteCustomSound) onDeleteCustomSound(sound.id);
                    }}
                    style={{
                      position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)',
                      fontSize: 14, opacity: 0.5, transition: 'opacity 0.2s', padding: 4
                    }}
                    onMouseEnter={(e) => e.target.style.opacity = 1}
                    onMouseLeave={(e) => e.target.style.opacity = 0.5}
                    title="删除音轨"
                  >
                    🗑️
                  </button>
                )}
                
                {!sound.isCustom && <div className="sound-indicator"></div>}
              </div>
              
              {isActive && (
                <div className="sound-volume-slider-container" onClick={(e) => e.stopPropagation()}>
                  <span style={{ fontSize: 11, opacity: 0.7 }}>🔊</span>
                  <input
                    type="range"
                    min="0"
                    max="100"
                    value={vol}
                    onChange={(e) => onVolumeChange && onVolumeChange(sound.id, parseInt(e.target.value))}
                    className="sound-volume-slider"
                  />
                  <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', minWidth: 28, textAlign: 'right' }}>{vol}%</span>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// 5. Streak Calendar Component
function StreakCalendar({ streakDays, onToggleDay, streakCount, totalMins }) {
  const days = ['日', '一', '二', '三', '四', '五', '六'];
  
  // Create an array of calendar days for the current week (June 14 - June 20)
  const dates = [
    { dayIdx: 0, dateNum: 14, label: '6/14' },
    { dayIdx: 1, dateNum: 15, label: '6/15' },
    { dayIdx: 2, dateNum: 16, label: '6/16' },
    { dayIdx: 3, dateNum: 17, label: '6/17' },
    { dayIdx: 4, dateNum: 18, label: '6/18', today: true },
    { dayIdx: 5, dateNum: 19, label: '6/19' },
    { dayIdx: 6, dateNum: 20, label: '6/20' },
  ];

  return (
    <div className="stats-row">
      <div className="stats-summary">
        <div className="stat-box">
          <span className="stat-val">{streakCount} 天</span>
          <span className="stat-lbl">连续正念</span>
        </div>
        <div className="stat-box">
          <span className="stat-val">{totalMins} 分钟</span>
          <span className="stat-lbl">累计正念时长</span>
        </div>
      </div>
      
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <span style={{ fontSize: 13, color: 'var(--text-secondary)', fontWeight: 500 }}>本周正念打卡</span>
        <div className="calendar-grid">
          {days.map((d, i) => (
            <div key={i} className="cal-day-header">{d}</div>
          ))}
          {dates.map((d) => {
            const isChecked = streakDays.includes(d.dayIdx);
            return (
              <div
                key={d.dayIdx}
                className={`cal-day ${isChecked ? 'active' : ''} ${d.today ? 'today' : ''}`}
                onClick={() => onToggleDay(d.dayIdx)}
                title={d.label}
              >
                <span style={{ fontSize: 10, opacity: 0.6 }}>{d.today ? '今天' : ''}</span>
                <span style={{ fontWeight: d.today ? 'bold' : 'normal' }}>{d.dateNum}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// 6. Tweaks Drawer Panel Component
function TweaksPanel({ 
  isOpen, 
  onClose, 
  inhaleTime, 
  setInhaleTime, 
  holdTime, 
  setHoldTime, 
  exhaleTime, 
  setExhaleTime, 
  fontStyle, 
  setFontStyle, 
  currentBgImage, 
  setBgImage,
  mainAudioSource,
  onMainAudioUpload,
  onMainAudioReset
}) {
  const fileInputRef = useRef(null);

  const bgOptions = [
    { id: 'gradient', name: '晨曦渐变 (Radial Gradient)' },
    { id: 'mist', name: '晨雾松林 (Forest Mist)' },
    { id: 'lake', name: '静谧湖泊 (Quiet Lake)' },
  ];

  const fontOptions = [
    { id: 'serif', name: '高雅宋体 (Noto Serif SC / Serif)' },
    { id: 'sans', name: '极简无衬线 (PingFang / Sans-Serif)' },
  ];

  const handleUploadButtonClick = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  return (
    <>
      <div className={`overlay ${isOpen ? 'visible' : ''}`} onClick={onClose} />
      <div className={`tweaks-drawer ${isOpen ? 'open' : ''}`}>
        <div className="tweaks-header">
          <h3 style={{ fontSize: 18, fontFamily: 'var(--font-serif)' }}>调节面板 (Tweaks)</h3>
          <button onClick={onClose} style={{ fontSize: 20 }}>✕</button>
        </div>

        {/* Custom main audio entry */}
        <div className="tweak-section" style={{ borderBottom: '1px solid var(--border)', paddingBottom: 20 }}>
          <span className="tweak-title">🎚️ 自定义主音轨</span>
          <div className="tweak-control">
            <label className="tweak-label">上传您的本地冥想音频，替换今日推荐课程：</label>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 4 }}>
              <button 
                onClick={handleUploadButtonClick}
                className="tweaks-btn" 
                style={{ margin: 0, padding: '8px 16px', flex: 1, justifyContent: 'center' }}
              >
                <span>📤</span> {mainAudioSource ? '更换音频' : '上传音频'}
              </button>
              <input 
                ref={fileInputRef}
                type="file" 
                accept="audio/*" 
                onChange={onMainAudioUpload} 
                style={{ position: 'absolute', width: 1, height: 1, opacity: 0, overflow: 'hidden', zIndex: -1, pointerEvents: 'none' }} 
              />
              {mainAudioSource && (
                <button 
                  onClick={onMainAudioReset}
                  className="tweaks-btn"
                  style={{ color: '#ff5f57', borderColor: 'rgba(255, 95, 87, 0.2)', padding: '8px 12px' }}
                  title="还原为默认音频"
                >
                  ✕ 还原
                </button>
              )}
            </div>
            {mainAudioSource && (
              <div style={{ 
                fontSize: 12, 
                color: 'var(--accent)', 
                marginTop: 8, 
                wordBreak: 'break-all', 
                backgroundColor: 'var(--accent-light)', 
                padding: '6px 12px', 
                borderRadius: 'var(--radius-sm)',
                border: '1px solid var(--border)'
              }}>
                <strong>当前已载入:</strong> {mainAudioSource.name}
              </div>
            )}
          </div>
        </div>

        <div className="tweak-section">
          <span className="tweak-title">呼吸阶段时长 (秒)</span>
          <div className="tweak-control">
            <label className="tweak-label">吸气 (Inhale): {inhaleTime}s</label>
            <input
              type="range"
              min="2"
              max="10"
              value={inhaleTime}
              onChange={(e) => setInhaleTime(parseInt(e.target.value))}
              className="tweak-range"
            />
          </div>
          <div className="tweak-control">
            <label className="tweak-label">吸气后屏气 (Hold): {holdTime}s</label>
            <input
              type="range"
              min="0"
              max="10"
              value={holdTime}
              onChange={(e) => setHoldTime(parseInt(e.target.value))}
              className="tweak-range"
            />
          </div>
          <div className="tweak-control">
            <label className="tweak-label">呼气 (Exhale): {exhaleTime}s</label>
            <input
              type="range"
              min="2"
              max="10"
              value={exhaleTime}
              onChange={(e) => setExhaleTime(parseInt(e.target.value))}
              className="tweak-range"
            />
          </div>
        </div>

        <div className="tweak-section">
          <span className="tweak-title">排版与背景</span>
          <div className="tweak-control">
            <label className="tweak-label">首选字体类型</label>
            <select
              value={fontStyle}
              onChange={(e) => setFontStyle(e.target.value)}
              className="tweak-select"
            >
              {fontOptions.map(f => (
                <option key={f.id} value={f.id}>{f.name}</option>
              ))}
            </select>
          </div>
          <div className="tweak-control">
            <label className="tweak-label">背景画卷</label>
            <select
              value={currentBgImage}
              onChange={(e) => setBgImage(e.target.value)}
              className="tweak-select"
            >
              {bgOptions.map(b => (
                <option key={b.id} value={b.id}>{b.name}</option>
              ))}
            </select>
          </div>
        </div>
        
        <div style={{ marginTop: 'auto', fontSize: 12, color: 'var(--text-tertiary)', borderTop: '1px solid var(--border)', paddingTop: 16 }}>
          baoyu-design · 本地交互原型调试面板
        </div>
      </div>
    </>
  );
}

Object.assign(window, {
  BreathingBall,
  AudioPlayer,
  MoodSlider,
  Soundscapes,
  StreakCalendar,
  TweaksPanel
});
