const { useState, useEffect, useRef } = React;

function App() {
  const appContainerRef = useRef(null);
  const bannerRef = useRef(null);
  const bentoMeditationRef = useRef(null);
  const { dailyMeditation, initialStreakDays } = window.meditationData;

  // 1. Navigation state
  const [currentTab, setCurrentTab] = useState('home'); // 'home', 'breath', 'sounds', 'stats'
  const [currentScheme, setCurrentScheme] = useState('card'); // 'card', 'bento' (home tab layout schemes)
  const [theme, setTheme] = useState('light'); // 'light', 'dark'
  
  // 2. Tweaks panel state
  const [isTweaksOpen, setIsTweaksOpen] = useState(false);
  const [inhaleTime, setInhaleTime] = useState(4);
  const [holdTime, setHoldTime] = useState(4);
  const [exhaleTime, setExhaleTime] = useState(4);
  const [fontStyle, setFontStyle] = useState('serif');
  const [bgImage, setBgImage] = useState('gradient');

  // 3. App business logic state
  const [isAudioPlaying, setIsAudioPlaying] = useState(false);
  const [isBreathPlaying, setIsBreathPlaying] = useState(false);
  const [moodValue, setMoodValue] = useState(60);
  const [selectedSounds, setSelectedSounds] = useState([]); // Empty on load to respect autoplay policy
  const [soundVolumes, setSoundVolumes] = useState({ rain: 15, fire: 30, wave: 20, wind: 10 });
  const [streakDays, setStreakDays] = useState(initialStreakDays);
  const [totalMins, setTotalMins] = useState(85);

  // 4. Custom audio upload states
  const [mainAudioSource, setMainAudioSource] = useState(null); // { name, url }
  const [customSounds, setCustomSounds] = useState([]); // Array of { id, name, url }

  // Mock recent records
  const recentRecords = [
    { date: "今日 6/18", title: "深林晨露 · 觉知当下", duration: "15 分钟", mood: "心平气和 😌" },
    { date: "周二 6/16", title: "正念呼吸 · 基础调节", duration: "10 分钟", mood: "心绪微动 😐" },
    { date: "周一 6/15", title: "深夜静修 · 渐入梦乡", duration: "20 分钟", mood: "物我两忘 😌" },
    { date: "周日 6/14", title: "清晨觉醒 · 活在当下", duration: "15 分钟", mood: "心平气和 🙂" }
  ];

  // Apply theme to document
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  // Apply font family to document body
  useEffect(() => {
    if (fontStyle === 'serif') {
      document.body.style.setProperty('--font-serif', '-apple-system-ui-serif, ui-serif, "Georgia", "Songti SC", "Noto Serif SC", "Source Han Serif SC", serif');
      document.body.style.fontFamily = 'var(--font-serif)';
    } else {
      document.body.style.setProperty('--font-serif', 'var(--font-sans)');
      document.body.style.fontFamily = 'var(--font-sans)';
    }
  }, [fontStyle]);

  // Audio reactive background animation for the entire canvas and banner
  useEffect(() => {
    let animationFrameId;
    let time = 0;

    const updateBannerStyle = () => {
      time += 0.02;
      let amp = 0;
      if (window.zenAudio) {
        amp = window.zenAudio.getAverageAmplitude(); // 0 to 255
      }

      const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
      // Low ceiling for high responsiveness
      const sensitivityCeiling = 45;
      const normalizedAmp = Math.min(1, amp / sensitivityCeiling);

      // 1. Update full-screen app container background (canvas)
      if (appContainerRef.current) {
        const x = 50 + Math.sin(time * 0.5) * 15 + (normalizedAmp * 4);
        const y = 45 + Math.cos(time * 0.4) * 15 + (normalizedAmp * 4);

        let color1, color2;
        if (currentTheme === 'dark') {
          let baseHue1 = 120, baseHue2 = 140, sat = 12, light1 = 11, light2 = 7;
          if (bgImage === 'mist') {
            baseHue1 = 215; baseHue2 = 230; sat = 15; light1 = 12; light2 = 8;
          } else if (bgImage === 'lake') {
            baseHue1 = 245; baseHue2 = 270; sat = 15; light1 = 12; light2 = 9;
          }
          
          const hueShift = normalizedAmp * 40;
          const satShift = normalizedAmp * 25;
          const lightShift1 = normalizedAmp * 8;
          const lightShift2 = normalizedAmp * 4;

          color1 = `hsl(${baseHue1 + hueShift}, ${sat + satShift}%, ${light1 + lightShift1}%)`;
          color2 = `hsl(${baseHue2 + hueShift * 0.5}, ${sat + satShift * 0.5}%, ${light2 + lightShift2}%)`;
        } else {
          let baseHue1 = 42, baseHue2 = 75, sat = 20, light1 = 94, light2 = 86;
          if (bgImage === 'mist') {
            baseHue1 = 210; baseHue2 = 225; sat = 18; light1 = 92; light2 = 85;
          } else if (bgImage === 'lake') {
            baseHue1 = 235; baseHue2 = 255; sat = 20; light1 = 92; light2 = 84;
          }

          const hueShift = normalizedAmp * 45;
          const satShift = normalizedAmp * 20;
          const lightShift1 = -normalizedAmp * 5;
          const lightShift2 = -normalizedAmp * 3;

          color1 = `hsl(${baseHue1 + hueShift}, ${sat + satShift}%, ${light1 + lightShift1}%)`;
          color2 = `hsl(${baseHue2 + hueShift * 0.5}, ${sat + satShift * 0.5}%, ${light2 + lightShift2}%)`;
        }

        appContainerRef.current.style.background = `radial-gradient(circle at ${x}% ${y}%, ${color1} 0%, ${color2} 100%)`;
      }

      // 2. Update homepage daily banner background
      if (bannerRef.current) {
        let bannerColor1, bannerColor2;
        if (currentTheme === 'dark') {
          let bHue1 = 120, bHue2 = 140, bSat = 15, bLt1 = 18, bLt2 = 12;
          if (bgImage === 'mist') {
            bHue1 = 215; bHue2 = 230; bSat = 15; bLt1 = 18; bLt2 = 12;
          } else if (bgImage === 'lake') {
            bHue1 = 245; bHue2 = 270; bSat = 15; bLt1 = 18; bLt2 = 12;
          }
          const hueShift = normalizedAmp * 45;
          const satShift = normalizedAmp * 25;
          const pulseLight = normalizedAmp * 12;
          
          bannerColor1 = `hsl(${bHue1 + hueShift}, ${bSat + satShift}%, ${bLt1 + pulseLight}%)`;
          bannerColor2 = `hsl(${bHue2 + hueShift * 0.5}, ${bSat + satShift * 0.5}%, ${bLt2 + pulseLight * 0.5}%)`;
        } else {
          let bHue1 = 40, bHue2 = 60, bSat = 18, bLt1 = 88, bLt2 = 82;
          if (bgImage === 'mist') {
            bHue1 = 210; bHue2 = 220; bSat = 12; bLt1 = 85; bLt2 = 75;
          } else if (bgImage === 'lake') {
            bHue1 = 230; bHue2 = 240; bSat = 25; bLt1 = 82; bLt2 = 72;
          }
          const hueShift = normalizedAmp * 45;
          const satShift = normalizedAmp * 15;
          const pulseLight = normalizedAmp * 6;

          bannerColor1 = `hsl(${bHue1 + hueShift}, ${bSat + satShift}%, ${bLt1 + pulseLight}%)`;
          bannerColor2 = `hsl(${bHue2 + hueShift * 0.5}, ${bSat + satShift * 0.5}%, ${bLt2 - pulseLight * 0.5}%)`;
        }

        const bx = 70 + Math.sin(time) * 10 + normalizedAmp * 8;
        const by = 30 + Math.cos(time) * 10 + normalizedAmp * 8;

        bannerRef.current.style.background = `radial-gradient(circle at ${bx}% ${by}%, ${bannerColor1} 0%, ${bannerColor2} 100%)`;
        
        const pattern = bannerRef.current.querySelector('.immersive-bg-pattern');
        if (pattern) {
          pattern.style.transform = `scale(${1 + normalizedAmp * 0.15})`;
          pattern.style.opacity = `${0.15 + normalizedAmp * 0.5}`;
        }

        const enso = bannerRef.current.querySelector('.zen-enso-circle');
        if (enso) {
          enso.style.transform = `translateY(-50%) scale(${1 + normalizedAmp * 0.18})`;
          enso.style.borderColor = currentTheme === 'dark' 
            ? `hsla(120, ${12 + normalizedAmp * 20}%, 55%, ${0.15 + normalizedAmp * 0.35})`
            : `hsla(75, ${20 + normalizedAmp * 20}%, 45%, ${0.20 + normalizedAmp * 0.35})`;
          enso.style.boxShadow = currentTheme === 'dark'
            ? `0 0 ${30 + normalizedAmp * 50}px rgba(141, 164, 141, ${0.08 + normalizedAmp * 0.25})`
            : `0 0 ${30 + normalizedAmp * 50}px rgba(93, 109, 93, ${0.05 + normalizedAmp * 0.20})`;
        }
      }

      // 3. Update homepage Bento meditation cell background
      if (bentoMeditationRef.current) {
        let baseHue = 40;
        let sat = 18;
        let glowLight = 75;
        if (currentTheme === 'dark') {
          glowLight = 20;
          if (bgImage === 'mist') { baseHue = 215; sat = 15; }
          else if (bgImage === 'lake') { baseHue = 245; sat = 15; }
          else { baseHue = 120; sat = 12; }
        } else {
          glowLight = 75;
          if (bgImage === 'mist') { baseHue = 210; sat = 12; }
          else if (bgImage === 'lake') { baseHue = 230; sat = 25; }
        }
        
        const hueShift = normalizedAmp * 45;
        const alpha = 0.05 + normalizedAmp * 0.25;
        bentoMeditationRef.current.style.background = `linear-gradient(to bottom right, var(--bg-card) 55%, hsla(${baseHue + hueShift}, ${sat + 10}%, ${glowLight}%, ${alpha}))`;
      }

      animationFrameId = requestAnimationFrame(updateBannerStyle);
    };

    updateBannerStyle();

    return () => {
      cancelAnimationFrame(animationFrameId);
    };
  }, [bgImage]);

  // Handle custom main audio upload
  const handleMainAudioUpload = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    
    // Stop current playing audio
    if (isAudioPlaying) {
      setIsAudioPlaying(false);
      if (window.zenAudio) {
        window.zenAudio.stopMusic();
        window.zenAudio.stopCustomSound('main_meditation');
      }
    }

    const url = URL.createObjectURL(file);
    setMainAudioSource({
      name: file.name.substring(0, 25) + (file.name.length > 25 ? '...' : ''),
      url
    });
  };

  const handleMainAudioReset = () => {
    if (isAudioPlaying) {
      setIsAudioPlaying(false);
      if (window.zenAudio) {
        window.zenAudio.stopCustomSound('main_meditation');
      }
    }
    setMainAudioSource(null);
  };

  // Handle custom background soundscape upload
  const handleCustomSoundUpload = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const url = URL.createObjectURL(file);
    const id = `custom_${Date.now()}`;
    const newSound = {
      id,
      name: file.name.substring(0, 15) + (file.name.length > 15 ? '...' : ''),
      url
    };
    setCustomSounds([...customSounds, newSound]);
    setSoundVolumes(prev => ({ ...prev, [id]: 30 }));
  };

  const handleDeleteCustomSound = (soundId) => {
    // Stop if playing
    if (selectedSounds.includes(soundId)) {
      setSelectedSounds(selectedSounds.filter(id => id !== soundId));
      if (window.zenAudio) window.zenAudio.stopCustomSound(soundId);
    }
    setCustomSounds(customSounds.filter(s => s.id !== soundId));
  };

  // Toggle daily meditation audio
  const handleToggleAudio = () => {
    const nextPlaying = !isAudioPlaying;
    setIsAudioPlaying(nextPlaying);
    if (window.zenAudio) {
      if (nextPlaying) {
        if (mainAudioSource) {
          window.zenAudio.startCustomSound('main_meditation', mainAudioSource.url);
          // Set to comfortable volume
          window.zenAudio.setVolume('main_meditation', 0.8);
        } else {
          window.zenAudio.startMusic();
        }
      } else {
        if (mainAudioSource) {
          window.zenAudio.stopCustomSound('main_meditation');
        } else {
          window.zenAudio.stopMusic();
        }
      }
    }
  };

  // Toggle background soundscapes (white noise)
  const handleToggleSound = (soundId) => {
    if (selectedSounds.includes(soundId)) {
      setSelectedSounds(selectedSounds.filter(id => id !== soundId));
      if (window.zenAudio) {
        if (soundId.startsWith('custom_')) {
          window.zenAudio.stopCustomSound(soundId);
        } else {
          window.zenAudio.stopSound(soundId);
        }
      }
    } else {
      setSelectedSounds([...selectedSounds, soundId]);
      if (window.zenAudio) {
        if (soundId.startsWith('custom_')) {
          const customObj = customSounds.find(s => s.id === soundId);
          if (customObj) {
            window.zenAudio.startCustomSound(soundId, customObj.url);
            window.zenAudio.setVolume(soundId, (soundVolumes[soundId] || 30) / 100);
          }
        } else {
          window.zenAudio.startSound(soundId);
          window.zenAudio.setVolume(soundId, (soundVolumes[soundId] || 15) / 100);
        }
      }
    }
  };

  // Adjust volume of soundscape
  const handleVolumeChange = (soundId, value) => {
    setSoundVolumes(prev => ({ ...prev, [soundId]: value }));
    if (window.zenAudio) {
      window.zenAudio.setVolume(soundId, value / 100);
    }
  };

  // Toggle calendar days
  const handleToggleDay = (dayIdx) => {
    if (streakDays.includes(dayIdx)) {
      setStreakDays(streakDays.filter(idx => idx !== dayIdx));
      setTotalMins(prev => Math.max(0, prev - 15));
    } else {
      setStreakDays([...streakDays, dayIdx].sort());
      setTotalMins(prev => prev + 15);
    }
  };

  // Toggle breathing ball play
  const handleToggleBreath = () => {
    const nextPlaying = !isBreathPlaying;
    setIsBreathPlaying(nextPlaying);
    if (nextPlaying && window.zenAudio) {
      window.zenAudio.playBowl();
    }
  };

  const streakCount = streakDays.length;

  const renderActiveTabContent = () => {
    switch (currentTab) {
      case 'home':
        if (currentScheme === 'card') {
          return (
            <div className="scheme-card-view">
              {/* Banner element containing daily meditation player */}
              <div className="immersive-banner" ref={bannerRef}>
                <div className="immersive-bg-pattern" style={{ transition: 'transform 0.1s ease, opacity 0.1s ease' }}></div>
                <div className="immersive-tag">
                  <span>DAILY PRACTICE</span>
                </div>

                {/* Right-side Zen Graphic & Quote */}
                <div className="zen-enso-circle" style={{ transition: 'transform 0.1s ease, border-color 0.1s ease, box-shadow 0.1s ease' }}></div>
                <div className="zen-quote-container">
                  <p className="zen-quote-text">“ 虚室生白，吉祥止止。心若安歇，何处不是清风拂面。”</p>
                  <span className="zen-quote-author">— 每日正念</span>
                </div>

                <div className="immersive-banner-content" style={{ width: '100%' }}>
                  <div style={{ maxWidth: '60%' }}>
                    <AudioPlayer 
                      themeTitle={mainAudioSource ? `自定义音频: ${mainAudioSource.name}` : dailyMeditation.title}
                      themeSubtitle={mainAudioSource ? "来自您的本地上传" : dailyMeditation.subtitle}
                      isPlaying={isAudioPlaying}
                      onTogglePlay={handleToggleAudio}
                    />
                  </div>
                </div>
              </div>

              {/* Left side column: Breathing & Mood */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
                <div className="zen-card">
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
                    <h3 style={{ fontSize: 18, fontFamily: 'var(--font-serif)' }}>呼吸训练</h3>
                    <button 
                      onClick={handleToggleBreath}
                      style={{ fontSize: 14, color: 'var(--accent)', fontWeight: 500 }}
                    >
                      {isBreathPlaying ? '停止' : '开始'}
                    </button>
                  </div>
                  <BreathingBall 
                    isPlaying={isBreathPlaying}
                    inhaleTime={inhaleTime}
                    holdTime={holdTime}
                    exhaleTime={exhaleTime}
                    holdTime2={holdTime}
                  />
                </div>

                <div className="zen-card">
                  <MoodSlider value={moodValue} onChange={setMoodValue} />
                </div>
              </div>

              {/* Right side column: Calendar & Soundscapes */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
                <div className="zen-card">
                  <h3 style={{ fontSize: 18, marginBottom: 20, fontFamily: 'var(--font-serif)' }}>正念日历</h3>
                  <StreakCalendar 
                    streakDays={streakDays}
                    onToggleDay={handleToggleDay}
                    streakCount={streakCount}
                    totalMins={totalMins}
                  />
                </div>

                <div className="zen-card">
                  <Soundscapes 
                    selectedSounds={selectedSounds}
                    onToggleSound={handleToggleSound}
                    volumes={soundVolumes}
                    onVolumeChange={handleVolumeChange}
                    customSounds={customSounds}
                    onDeleteCustomSound={handleDeleteCustomSound}
                  />
                </div>
              </div>
            </div>
          );
        } else {
          // Bento layout
          return (
            <div className="scheme-bento-view">
              {/* Cell 1: Daily Meditation */}
              <div className="bento-item bento-item-1" ref={bentoMeditationRef}>
                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                    <span style={{ fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-secondary)' }}>今日冥想</span>
                  </div>
                  <h2 style={{ fontSize: 32, fontFamily: 'var(--font-serif)', marginBottom: 8 }}>
                    {mainAudioSource ? `自定义音频: ${mainAudioSource.name}` : dailyMeditation.title}
                  </h2>
                  <p style={{ fontSize: 14, color: 'var(--text-secondary)', maxWidth: '90%' }}>
                    {mainAudioSource ? "播放您上传的本地音频课" : dailyMeditation.subtitle}
                  </p>
                </div>

                <AudioPlayer 
                  themeTitle=""
                  themeSubtitle=""
                  isPlaying={isAudioPlaying}
                  onTogglePlay={handleToggleAudio}
                />
              </div>

              {/* Cell 2: Breathing Ball */}
              <div className="bento-item bento-item-2">
                <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%', alignItems: 'center' }}>
                  <span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>呼吸球</span>
                  <button 
                    onClick={handleToggleBreath}
                    style={{ fontSize: 13, color: 'var(--accent)', fontWeight: 600 }}
                  >
                    {isBreathPlaying ? '暂停' : '启动'}
                  </button>
                </div>
                <BreathingBall 
                  isPlaying={isBreathPlaying}
                  inhaleTime={inhaleTime}
                  holdTime={holdTime}
                  exhaleTime={exhaleTime}
                  holdTime2={holdTime}
                />
              </div>

              {/* Cell 3: Streak Calendar */}
              <div className="bento-item bento-item-3">
                <StreakCalendar 
                  streakDays={streakDays}
                  onToggleDay={handleToggleDay}
                  streakCount={streakCount}
                  totalMins={totalMins}
                />
              </div>

              {/* Cell 4: Mood Slider */}
              <div className="bento-item bento-item-4">
                <MoodSlider value={moodValue} onChange={setMoodValue} />
              </div>

              {/* Cell 5: Soundscapes Grid */}
              <div className="bento-item bento-item-5">
                <Soundscapes 
                  selectedSounds={selectedSounds}
                  onToggleSound={handleToggleSound}
                  volumes={soundVolumes}
                  onVolumeChange={handleVolumeChange}
                  customSounds={customSounds}
                  onDeleteCustomSound={handleDeleteCustomSound}
                />
              </div>
            </div>
          );
        }

      case 'breath':
        return (
          <div className="scheme-breath-view">
            <BreathingBall 
              isPlaying={isBreathPlaying}
              inhaleTime={inhaleTime}
              holdTime={holdTime}
              exhaleTime={exhaleTime}
              holdTime2={holdTime}
            />

            <div className="breath-btn-group">
              <button 
                onClick={handleToggleBreath}
                className="play-btn"
                style={{ width: 'auto', padding: '0 32px', borderRadius: 'var(--radius-full)' }}
              >
                {isBreathPlaying ? '停止呼吸引导' : '开始正念呼吸'}
              </button>
            </div>

            {/* Soundscape overlay indicator */}
            {selectedSounds.length > 0 && (
              <div style={{
                position: 'absolute', bottom: 32, display: 'flex', gap: 12,
                fontSize: 12, color: 'var(--text-secondary)', alignItems: 'center',
                backgroundColor: 'var(--bg-app)', padding: '6px 16px', borderRadius: 'var(--radius-full)',
                border: '1px solid var(--border)'
              }}>
                <span>伴鸣开启中:</span>
                {selectedSounds.map(id => {
                  const custom = customSounds.find(s => s.id === id);
                  return (
                    <span key={id} style={{ fontWeight: 500 }}>
                      {custom ? `🎵 ${custom.name}` : id === 'rain' ? '🌧️ 山雨' : id === 'fire' ? '🔥 柴火' : id === 'wave' ? '🌊 潮汐' : '🍃 山风'}
                    </span>
                  );
                })}
              </div>
            )}
          </div>
        );

      case 'sounds':
        return (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
            <div className="zen-card" style={{ padding: '40px 48px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                <h2 style={{ fontSize: 24, fontFamily: 'var(--font-serif)' }}>声音自然工坊 (Soundscape Studio)</h2>
                <label className="tweaks-btn" style={{ cursor: 'pointer' }}>
                  <span>➕</span> 导入本地音频
                  <input type="file" accept="audio/*" onChange={handleCustomSoundUpload} style={{ display: 'none' }} />
                </label>
              </div>
              <p style={{ fontSize: 15, color: 'var(--text-secondary)', marginBottom: 32 }}>
                微调各种大自然低语的分贝，并支持**上传您本地的 MP3/WAV 音频文件**，混合打造您专属的正念白噪音背景空间。
              </p>
              
              <Soundscapes 
                selectedSounds={selectedSounds}
                onToggleSound={handleToggleSound}
                volumes={soundVolumes}
                onVolumeChange={handleVolumeChange}
                customSounds={customSounds}
                onDeleteCustomSound={handleDeleteCustomSound}
              />
            </div>

            {/* Special Sing Bowl interactive card */}
            <div className="zen-card" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <h3 style={{ fontSize: 20, fontFamily: 'var(--font-serif)', marginBottom: 6 }}>颂钵磬音 (Tibetan Singing Bowl)</h3>
                <p style={{ fontSize: 14, color: 'var(--text-secondary)' }}>敲击颂钵发出悠远空灵的金属回响，快速安定心神，常用于冥想开始与结束。</p>
              </div>
              <button 
                onClick={() => window.zenAudio && window.zenAudio.playBowl()}
                className="play-btn"
                style={{ width: 'auto', padding: '0 24px', borderRadius: 'var(--radius-full)', gap: 8 }}
              >
                <span>🔔</span> 敲击颂钵
              </button>
            </div>
          </div>
        );

      case 'stats':
        return (
          <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 32 }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
              {/* Highlight summary numbers */}
              <div className="zen-card" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24, textAlign: 'center' }}>
                <div style={{ borderRight: '1px solid var(--border)' }}>
                  <div style={{ fontSize: 36, fontFamily: 'var(--font-serif)', color: 'var(--accent)' }}>{streakCount} 天</div>
                  <div style={{ fontSize: 13, color: 'var(--text-secondary)' }}>连续打卡</div>
                </div>
                <div style={{ borderRight: '1px solid var(--border)' }}>
                  <div style={{ fontSize: 36, fontFamily: 'var(--font-serif)', color: 'var(--accent)' }}>{totalMins} 分钟</div>
                  <div style={{ fontSize: 13, color: 'var(--text-secondary)' }}>累计修行</div>
                </div>
                <div>
                  <div style={{ fontSize: 36, fontFamily: 'var(--font-serif)', color: 'var(--accent)' }}>初觉</div>
                  <div style={{ fontSize: 13, color: 'var(--text-secondary)' }}>觉悟阶段</div>
                </div>
              </div>

              {/* Weekly SVG Bar Chart */}
              <div className="zen-card">
                <h3 style={{ fontSize: 18, fontFamily: 'var(--font-serif)', marginBottom: 20 }}>本周冥想曲线 (分钟)</h3>
                <svg viewBox="0 0 500 200" style={{ width: '100%', height: 'auto' }}>
                  {/* Axis lines */}
                  <line x1="40" y1="160" x2="480" y2="160" className="chart-axis" />
                  <line x1="40" y1="20" x2="40" y2="160" className="chart-axis" />

                  {/* Grid Lines */}
                  <line x1="40" y1="110" x2="480" y2="110" style={{ stroke: 'var(--border)', strokeDasharray: '4 4' }} />
                  <line x1="40" y1="60" x2="480" y2="60" style={{ stroke: 'var(--border)', strokeDasharray: '4 4' }} />

                  {/* Axis Labels */}
                  <text x="15" y="163" className="chart-text">0</text>
                  <text x="15" y="113" className="chart-text">15</text>
                  <text x="15" y="63" className="chart-text">30</text>

                  {/* Bars & Labels */}
                  {/* Sun (15m) */}
                  <rect x="65" y="110" width="30" height="50" rx="3" className="chart-bar" />
                  <text x="73" y="180" className="chart-text">日</text>
                  <text x="73" y="100" className="chart-text">15</text>

                  {/* Mon (20m) */}
                  <rect x="125" y="93" width="30" height="67" rx="3" className="chart-bar" />
                  <text x="133" y="180" className="chart-text">一</text>
                  <text x="133" y="83" className="chart-text">20</text>

                  {/* Tue (10m) */}
                  <rect x="185" y="127" width="30" height="33" rx="3" className="chart-bar" />
                  <text x="193" y="180" className="chart-text">二</text>
                  <text x="193" y="117" className="chart-text">10</text>

                  {/* Wed (0m) */}
                  <rect x="245" y="158" width="30" height="2" rx="1" className="chart-bar" />
                  <text x="253" y="180" className="chart-text">三</text>
                  <text x="253" y="148" className="chart-text">0</text>

                  {/* Thu (15m) */}
                  <rect x="305" y="110" width="30" height="50" rx="3" className="chart-bar" />
                  <text x="313" y="180" className="chart-text">四</text>
                  <text x="313" y="100" className="chart-text">15</text>

                  {/* Fri (25m) */}
                  <rect x="365" y="77" width="30" height="83" rx="3" className="chart-bar" />
                  <text x="373" y="180" className="chart-text">五</text>
                  <text x="373" y="67" className="chart-text">25</text>

                  {/* Sat (0m initially, let's say 0m) */}
                  <rect x="425" y="158" width="30" height="2" rx="1" className="chart-bar" />
                  <text x="433" y="180" className="chart-text">六</text>
                  <text x="433" y="148" className="chart-text">0</text>
                </svg>
              </div>

              {/* Recent Records list */}
              <div className="zen-card">
                <h3 style={{ fontSize: 18, fontFamily: 'var(--font-serif)', marginBottom: 8 }}>正念修行随笔</h3>
                <div className="record-list">
                  {recentRecords.map((r, i) => (
                    <div key={i} className="record-item">
                      <div>
                        <div style={{ fontSize: 14, fontWeight: 500 }}>{r.title}</div>
                        <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>{r.date} · 冥想时长 {r.duration}</div>
                      </div>
                      <span style={{ fontSize: 13, color: 'var(--accent)', fontWeight: 500 }}>{r.mood}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Right column: Streak Calendar */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
              <div className="zen-card">
                <h3 style={{ fontSize: 18, fontFamily: 'var(--font-serif)', marginBottom: 20 }}>正念轨迹打卡</h3>
                <StreakCalendar 
                  streakDays={streakDays}
                  onToggleDay={handleToggleDay}
                  streakCount={streakCount}
                  totalMins={totalMins}
                />
              </div>

              <div className="zen-card">
                <h3 style={{ fontSize: 16, fontFamily: 'var(--font-serif)', marginBottom: 12 }}>修行心得</h3>
                <p style={{ fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.7 }}>
                  “学道如逆水行舟，一日正念，得一日之寂静清澄。无问结果，只专注于此刻的呼吸起落之间。”
                </p>
              </div>
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="app-container" ref={appContainerRef}>
      {/* 1. Sidebar Navigation */}
      <aside className="nav-sidebar">
        <div>
          <div className="brand">
            {theme === 'dark' ? (
              <svg className="brand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                <path strokeLinecap="round" strokeLinejoin="round" d="M21.752 15.002A9.718 9.718 0 0118 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 003 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 009.002-5.998z" />
              </svg>
            ) : (
              <svg className="brand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v1.5M12 19.5V21M3.07 12h1.5m16.36 0h1.5m-2.39-7.07l-1.06 1.06M6.34 17.66l-1.06 1.06m0-11.32l1.06 1.06m11.32 11.32l1.06-1.06M12 7.25a4.75 4.75 0 100 9.5 4.75 4.75 0 000-9.5z" />
              </svg>
            )}
            <span className="brand-name serif-font">息 · 冥想 (Breath)</span>
          </div>
          
          <nav className="nav-links">
            <div className="nav-section-title">正念空间</div>
            <button 
              className={`nav-item ${currentTab === 'home' ? 'active' : ''}`}
              onClick={() => setCurrentTab('home')}
            >
              <span>🏠</span> 首页
            </button>
            <button 
              className={`nav-item ${currentTab === 'breath' ? 'active' : ''}`}
              onClick={() => {
                setCurrentTab('breath');
                setCurrentScheme('breath'); // Sync scheme tab
              }}
            >
              <span>🌀</span> 沉浸呼吸
            </button>
            <button 
              className={`nav-item ${currentTab === 'sounds' ? 'active' : ''}`}
              onClick={() => setCurrentTab('sounds')}
            >
              <span>🎵</span> 声音图景
            </button>
            <button 
              className={`nav-item ${currentTab === 'stats' ? 'active' : ''}`}
              onClick={() => setCurrentTab('stats')}
            >
              <span>📈</span> 数据统计
            </button>
          </nav>
        </div>

        {/* User profile / theme toggle at bottom */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>界面主题</span>
            <button 
              onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
              style={{ fontSize: 18 }}
              title="切换暗黑模式"
            >
              {theme === 'light' ? '🌙' : '☀️'}
            </button>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, borderTop: '1px solid var(--border)', paddingTop: 16 }}>
            <div style={{ width: 36, height: 36, borderRadius: '50%', backgroundColor: 'var(--accent-light)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16 }}>
              🍵
            </div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>静心修行者</div>
              <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>连续正念 {streakCount} 天</div>
            </div>
          </div>
        </div>
      </aside>

      {/* 2. Main Layout Area */}
      <main className="main-layout">
        {/* Top Control Bar */}
        <header className="top-controller">
          <div>
            <h1 style={{ fontSize: 32, fontFamily: 'var(--font-serif)', marginBottom: 4 }}>正念觉察</h1>
            <div style={{ fontSize: 14, color: 'var(--text-secondary)' }}>
              {currentTab === 'home' && currentScheme === 'card' && '首页 · 方案一：沉浸式卡片布局'}
              {currentTab === 'home' && currentScheme === 'bento' && '首页 · 方案三：模块化 Bento 布局'}
              {currentTab === 'breath' && '沉浸呼吸 · 方案二：全屏静修呼吸布局'}
              {currentTab === 'sounds' && '声音工排 · 实时合成大自然白噪音'}
              {currentTab === 'stats' && '修行数据 · 正念打卡轨迹记录'}
            </div>
          </div>

          <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
            {/* Show layout tabs only when on the Home page */}
            {currentTab === 'home' && (
              <div className="scheme-selector">
                <button 
                  className={`scheme-tab ${currentScheme === 'card' ? 'active' : ''}`}
                  onClick={() => setCurrentScheme('card')}
                >
                  沉浸卡片式
                </button>
                <button 
                  className={`scheme-tab ${currentScheme === 'bento' ? 'active' : ''}`}
                  onClick={() => setCurrentScheme('bento')}
                >
                  模块磁贴式
                </button>
              </div>
            )}

            <button className="tweaks-btn" onClick={() => setIsTweaksOpen(true)}>
              <span>⚙️</span> 调节面板
            </button>
          </div>
        </header>

        {/* Render active tab content */}
        {renderActiveTabContent()}

        {/* Footer info */}
        <footer style={{ marginTop: 'auto', textAlign: 'center', padding: '40px 0 20px 0', borderTop: '1px solid var(--border)', fontSize: 12, color: 'var(--text-tertiary)' }}>
          息 · Breath Meditation App © 2026. Design Exploration using baoyu-design.
        </footer>
      </main>

      {/* 3. Tweaks Drawer Panel */}
      <TweaksPanel 
        isOpen={isTweaksOpen}
        onClose={() => setIsTweaksOpen(false)}
        inhaleTime={inhaleTime}
        setInhaleTime={setInhaleTime}
        holdTime={holdTime}
        setHoldTime={setHoldTime}
        exhaleTime={exhaleTime}
        setExhaleTime={setExhaleTime}
        fontStyle={fontStyle}
        setFontStyle={setFontStyle}
        currentBgImage={bgImage}
        setBgImage={setBgImage}
        mainAudioSource={mainAudioSource}
        onMainAudioUpload={handleMainAudioUpload}
        onMainAudioReset={handleMainAudioReset}
      />
    </div>
  );
}

// Mount the App component
const rootElement = document.getElementById('root');
const root = ReactDOM.createRoot(rootElement);
root.render(<App />);
