import { useState, useEffect, useRef } from 'react';
import MusicPlayer from './components/MusicPlayer';
import Timer from './components/Timer';
import Notes from './components/Notes';
import WhiteNoise from './components/WhiteNoise';
import KiraAvatar from './components/KiraAvatar';
import ChatBubble from './components/ChatBubble';
import PetZone from './components/PetZone';
import Wardrobe from './components/Wardrobe';
import Particles from './components/Particles';
import WelcomeScreen from './components/WelcomeScreen';
import Live2DStage from './components/Live2DStage';
import { SCENES, type Scene } from './components/scenes';
import { useConversation } from './hooks/useConversation';

export default function App() {
  const {
    messages,
    isConnected,
    isKiraSpeaking,
    isRecording,
    identified,
    preferences,
    loadingPrefs,
    identify,
    setPreference,
    sendText,
    startRecording,
    stopRecording,
    livePartial,
  } = useConversation();

  const [currentSceneId, setCurrentSceneId] = useState('cozy-room');
  const [currentOutfit, setCurrentOutfit] = useState('cozy-hoodie');
  const [currentAcc, setCurrentAcc] = useState<string | null>(null);
  const [textInput, setTextInput] = useState('');
  const [live2dReady, setLive2dReady] = useState(false);
  const kiraModelRef = useRef<any>(null);

  useEffect(() => {
    if (preferences.scene) setCurrentSceneId(preferences.scene);
    if (preferences.outfit) setCurrentOutfit(preferences.outfit);
    if (preferences.accessory) setCurrentAcc(preferences.accessory);
  }, [preferences.scene, preferences.outfit, preferences.accessory]);

  const currentScene: Scene = SCENES.find((s) => s.id === currentSceneId) ?? SCENES[0];

  const handleSceneChange = (id: string) => {
    setCurrentSceneId(id);
    setPreference('scene', id);
  };

  const handleOutfitChange = (id: string) => {
    setCurrentOutfit(id);
    setPreference('outfit', id);
  };

  const handleAccessoryChange = (id: string | null) => {
    setCurrentAcc(id);
    setPreference('accessory', id || '');
  };

  const handleTalkToggle = () => {
    if (isRecording) stopRecording();
    else startRecording();
  };

  const handleTextSend = () => {
    if (!textInput.trim()) return;
    sendText(textInput.trim());
    setTextInput('');
  };

  const handleWelcome = (name: string) => {
    identify(name);
  };

  if (!identified && !loadingPrefs) {
    const savedId = localStorage.getItem('kira-user-id');
    if (!savedId) {
      return <WelcomeScreen onComplete={handleWelcome} />;
    }
    return (
      <div className="h-screen flex items-center justify-center bg-gradient-to-br from-kira-bg via-kira-glow to-kira-pink/20">
        <div className="max-w-sm w-full p-6 text-center space-y-4">
          <div className="w-16 h-16 rounded-full bg-gradient-to-br from-kira-pink via-kira-lav to-kira-mint p-1 mx-auto" style={{ animation: 'pulse-glow 3s ease-in-out infinite' }}><div className="w-full h-full rounded-full bg-white flex items-center justify-center"><span className="text-2xl">🌸</span></div></div>
          <p className="text-kira-plum/60 text-sm">coming back? say your name</p>
          <WelcomeScreen onComplete={handleWelcome} isCompact />
        </div>
        <style>{'@keyframes pulse-glow{0%,100%{box-shadow:0 0 12px rgba(255,182,193,0.3)}50%{box-shadow:0 0 28px rgba(216,180,254,0.5)}}'}</style>
      </div>
    );
  }

  const userName = preferences.name || 'there';

  return (
    <div className="h-screen relative transition-all duration-1000" style={{ background: currentScene.gradient }}>
      {/* Single Live2D canvas: both Kira and Mochi share one WebGL context */}
      <Live2DStage
        onKiraReady={(model) => { kiraModelRef.current = model; }}
        onReady={() => setLive2dReady(true)}
        isSpeaking={isKiraSpeaking}
      />

      <Particles type={currentScene.particles ?? 'none'} />
      <div className="relative z-20 h-full flex flex-col">
        {/* ── Top bar: scene selector + clock ── */}
        <div className="flex items-center justify-between px-5 py-3 shrink-0">
          <div className="flex items-center gap-1">
            {SCENES.map((s) => (
              <button key={s.id} onClick={() => handleSceneChange(s.id)}
                className={'w-8 h-8 rounded-full flex items-center justify-center text-sm transition-all '
                  + (s.id === currentSceneId ? 'bg-white/60 shadow-sm scale-110' : 'hover:bg-white/30')}>
                {s.icon}
              </button>
            ))}
          </div>
          <div className="flex items-center gap-4">
            <span className="text-kira-plum/30 text-xs font-medium">
              {new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} &middot; {new Date().toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' })}
            </span>
            <span className="text-xs text-kira-plum/20">🌸 body double</span>
          </div>
        </div>

        {/* ── Main three-column body ── */}
        <div className="flex-1 flex min-h-0 px-4 gap-4">
          {/* LEFT: Focus Timer + Chat + Input */}
          <div className="w-72 shrink-0 flex flex-col gap-3">
            <div className="shrink-0">
              <Timer />
            </div>
            <div className="shrink-0">
              <Notes />
            </div>
            <div className="shrink-0">
              <ChatBubble messages={messages} isKiraSpeaking={isKiraSpeaking} userName={userName} livePartial={livePartial} />
            </div>
            <div className="shrink-0 flex gap-2">
              <input
                value={textInput}
                onChange={(e) => setTextInput(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleTextSend()}
                placeholder={`hey ${userName}...`}
                className="flex-1 bg-white/40 rounded-xl px-3 py-2 text-sm text-kira-plum placeholder-kira-plum/30 border-0 focus:outline-none focus:ring-2 focus:ring-kira-pink/30"
              />
              <button onClick={handleTextSend} className="btn-kira px-4 text-sm shrink-0">Send</button>
            </div>
          </div>

          {/* CENTER: Avatar UI overlay (Live2D renders on the background stage) */}
          <div className="flex-1 min-w-0 rounded-2xl bg-transparent overflow-hidden">
            <KiraAvatar
              isSpeaking={isKiraSpeaking}
              isListening={isRecording}
              outfit={currentOutfit}
              accessory={currentAcc}
              onTalkToggle={handleTalkToggle}
              kiraModel={kiraModelRef.current}
              live2dReady={live2dReady}
            />
          </div>

          {/* RIGHT: Ambient + Companions */}
          <div className="w-64 shrink-0 flex flex-col gap-3 overflow-y-auto">
            <MusicPlayer />
            <WhiteNoise />
            <Wardrobe onOutfitChange={handleOutfitChange} onAccessoryChange={handleAccessoryChange} />
            <PetZone />
          </div>
        </div>

        {/* ── Bottom status bar ── */}
        <div className="shrink-0 px-5 py-2 flex items-center justify-between text-[11px] text-kira-plum/30">
          <div className="flex items-center gap-2">
            <span className={`w-1.5 h-1.5 rounded-full ${
              isRecording ? 'bg-red-400 animate-pulse'
              : isKiraSpeaking ? 'bg-kira-pink animate-pulse'
              : 'bg-kira-mint'
            }`} />
            {isRecording ? 'listening...' : isKiraSpeaking ? 'kira speaking...' : `kira's here for you, ${userName}`}
          </div>
          <div className="flex items-center gap-2">
            <span className={isConnected ? '' : 'text-red-300'}>{isConnected ? '' : 'reconnecting...'}</span>
            <span>💖</span>
          </div>
        </div>
      </div>
    </div>
  );
}
