// ftue.jsx — First-time user experience (90s onboarding)
const { useState, useEffect, useRef } = React;

function FTUE({ onFinish }) {
  const [step, setStep] = useState(0);
  const [goal, setGoal] = useState(null);
  const [state, setState] = useState(null);
  const next = () => setStep(s => s + 1);

  // auto-advance splash
  useEffect(() => {
    if (step === 0) { const t = setTimeout(next, 2400); return () => clearTimeout(t); }
  }, [step]);

  const screens = [
    <Splash key="0" onTap={next}/>,
    <PromiseScreen key="1" onNext={next}/>,
    <Goal key="2" value={goal} setValue={setGoal} onNext={next}/>,
    <CurState key="3" value={state} setValue={setState} onNext={next}/>,
    <FirstQuest key="4" onStart={next}/>,
    <FirstPlayer key="5" onDone={next}/>,
    <FirstDone key="6" onNext={next} onHome={onFinish}/>,
    <Reminder key="7" onFinish={onFinish}/>,
  ];
  return screens[step];
}

// Progress dots
function Dots({ n, i }) {
  return (
    <div style={{ display: 'flex', gap: 6, justifyContent: 'center', padding: '4px 0 18px' }}>
      {Array.from({ length: n }).map((_, k) => (
        <div key={k} style={{
          width: k === i ? 22 : 6, height: 6, borderRadius: 999,
          background: k === i ? T.coral : T.line2, transition: 'all .3s',
        }}/>
      ))}
    </div>
  );
}

// 0 — Splash
function Splash({ onTap }) {
  return (
    <div onClick={onTap} style={{
      position: 'absolute', inset: 0, cursor: 'pointer',
      background: `radial-gradient(130% 90% at 50% 18%, #5AA0FF 0%, ${T.coral} 46%, ${T.coralDark} 100%)`,
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      padding: '0 40px', textAlign: 'center',
    }}>
      <StatusBar light/>
      <div style={{ animation: 'fadeUp .8s ease' }}>
        <div style={{ position: 'relative', display: 'flex', justifyContent: 'center', marginBottom: 38 }}>
          <div style={{
            width: 120, height: 120, borderRadius: '50%',
            background: 'radial-gradient(circle at 38% 32%, #DCEBFF 0%, #FFF 30%, #CFE3FF 70%, #B5D4FF 100%)',
            boxShadow: '0 20px 60px rgba(0,0,0,0.22), inset 0 4px 14px rgba(255,255,255,0.7)',
            animation: 'avaBreath 3.6s ease-in-out infinite',
          }}/>
          <div style={{ position: 'absolute', inset: -26, borderRadius: '50%', border: '2px solid rgba(255,255,255,0.35)', animation: 'avaPing 2.6s ease-out infinite' }}/>
        </div>
        <div style={{ fontSize: 40, fontWeight: 800, color: '#fff', letterSpacing: -1, marginBottom: 22 }}>Fitbody</div>
        <div style={{ fontSize: 12, fontWeight: 800, color: 'rgba(255,255,255,0.85)', letterSpacing: 2, marginBottom: 8 }}>AVA</div>
        <div style={{ fontSize: 21, fontWeight: 600, color: '#fff', lineHeight: 1.45, letterSpacing: -0.3, maxWidth: 280 }}>
          “오늘은 10초만 움직여도<br/>시작이에요.”
        </div>
      </div>
      <div style={{ position: 'absolute', bottom: 54, fontSize: 13, color: 'rgba(255,255,255,0.7)', fontWeight: 600 }}>탭하여 계속</div>
    </div>
  );
}

// 1 — Product promise
function PromiseScreen({ onNext }) {
  const rows = [
    { icon: 'clock', t: '10초 ~ 2분', s: '하루 한 가지, 부담 없는 행동' },
    { icon: 'camera_off', t: '카메라 없이도 가능', s: '복장도 공간도 필요 없어요' },
    { icon: 'flame', t: '완료하면 XP와 Streak', s: '매일의 연결이 쌓여요' },
  ];
  return (
    <Screen bg={T.bg}>
      <div style={{ paddingTop: 18 }}>
        <AvaOrb size={56}/>
        <h1 style={{ fontSize: 30, fontWeight: 800, color: T.ink, letterSpacing: -0.6, lineHeight: 1.25, margin: '22px 0 8px' }}>
          Ava가 매일 하나의<br/>건강 Quest를 정해드려요
        </h1>
        <p style={{ fontSize: 16, color: T.ink2, lineHeight: 1.5, margin: '0 0 28px' }}>고를 필요 없어요. 오늘 할 행동 하나면 충분해요.</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {rows.map((r, i) => (
            <Card key={i} pad={16} style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 48, height: 48, borderRadius: 14, background: T.coralTint, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name={r.icon} size={24} color={T.coral} sw={2}/>
              </div>
              <div>
                <div style={{ fontSize: 16.5, fontWeight: 700, color: T.ink, letterSpacing: -0.3 }}>{r.t}</div>
                <div style={{ fontSize: 14, color: T.ink2, marginTop: 2 }}>{r.s}</div>
              </div>
            </Card>
          ))}
        </div>
      </div>
      <FloatCTA><Btn onClick={onNext}>시작하기</Btn></FloatCTA>
    </Screen>
  );
}

// Floating bottom CTA wrapper
function FloatCTA({ children, hint }) {
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0, padding: '14px 22px 30px',
      background: 'linear-gradient(transparent, rgba(255,255,255,0.96) 28%)',
    }}>
      {hint && <div style={{ textAlign: 'center', fontSize: 13, color: T.ink3, marginBottom: 10, fontWeight: 600 }}>{hint}</div>}
      {children}
    </div>
  );
}

// 2 — Goal selection
function Goal({ value, setValue, onNext }) {
  const opts = [
    { id: 'habit', label: '운동 습관 만들기', icon: 'flame' },
    { id: 'fit', label: '체력 올리기', icon: 'bolt' },
    { id: 'posture', label: '자세 개선', icon: 'target' },
    { id: 'fatigue', label: '피로 줄이기', icon: 'leaf' },
    { id: 'weight', label: '체중 관리', icon: 'dumbbell' },
    { id: 'sleep', label: '수면 루틴', icon: 'moon' },
  ];
  return (
    <Screen bg={T.bg}>
      <div style={{ paddingTop: 12 }}>
        <Dots n={3} i={0}/>
        <h1 style={{ fontSize: 27, fontWeight: 800, color: T.ink, letterSpacing: -0.5, lineHeight: 1.3, margin: '0 0 22px' }}>
          지금 가장 원하는<br/>변화는 무엇인가요?
        </h1>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {opts.map(o => (
            <BigChoice key={o.id} icon={o.icon} label={o.label} active={value === o.id} onClick={() => setValue(o.id)}/>
          ))}
        </div>
      </div>
      <FloatCTA><Btn onClick={onNext} disabled={!value}>계속</Btn></FloatCTA>
    </Screen>
  );
}

function BigChoice({ icon, label, active, onClick, sub }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 14, width: '100%', textAlign: 'left',
      padding: '14px 16px', borderRadius: 18, cursor: 'pointer', fontFamily: 'inherit',
      background: active ? T.coralTint : T.bg, transition: 'all .14s',
      boxShadow: active ? `inset 0 0 0 2px ${T.coral}` : `inset 0 0 0 1.5px ${T.line2}`,
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: 13, flexShrink: 0,
        background: active ? T.coral : T.surface2,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={icon} size={22} color={active ? '#fff' : T.ink2} sw={2}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 16.5, fontWeight: 700, color: active ? T.coralDark : T.ink, letterSpacing: -0.3 }}>{label}</div>
        {sub && <div style={{ fontSize: 13.5, color: T.ink2, marginTop: 1 }}>{sub}</div>}
      </div>
      <div style={{
        width: 24, height: 24, borderRadius: 999, flexShrink: 0,
        background: active ? T.coral : 'transparent',
        boxShadow: active ? 'none' : `inset 0 0 0 2px ${T.line2}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{active && <Icon name="check" size={15} color="#fff" sw={2.6}/>}</div>
    </button>
  );
}

// 3 — Current state
function CurState({ value, setValue, onNext }) {
  const opts = [
    { id: '10s', label: '10초만 가능', icon: 'clock' },
    { id: '1m', label: '1분 가능', icon: 'bolt' },
    { id: 'tired', label: '피곤해요', icon: 'moon' },
    { id: 'seated', label: '앉아서만 가능', icon: 'seat' },
  ];
  return (
    <Screen bg={T.bg}>
      <div style={{ paddingTop: 12 }}>
        <Dots n={3} i={1}/>
        <h1 style={{ fontSize: 27, fontWeight: 800, color: T.ink, letterSpacing: -0.5, lineHeight: 1.3, margin: '0 0 8px' }}>
          지금 바로 할 수 있는<br/>상태인가요?
        </h1>
        <p style={{ fontSize: 15.5, color: T.ink2, margin: '0 0 22px' }}>첫 Quest를 성공시키기 위한 질문이에요.</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {opts.map(o => (
            <BigChoice key={o.id} icon={o.icon} label={o.label} active={value === o.id} onClick={() => setValue(o.id)}/>
          ))}
        </div>
      </div>
      <FloatCTA><Btn onClick={onNext} disabled={!value}>계속</Btn></FloatCTA>
    </Screen>
  );
}

// 4 — Ava first quest
function FirstQuest({ onStart }) {
  return (
    <Screen bg={T.surface}>
      <div style={{ paddingTop: 16 }}>
        <Dots n={3} i={2}/>
        <AvaSays size={50} style={{ marginBottom: 22 }}>
          좋아요. 첫날은 성공 확률을 높이기 위해 <b style={{ color: T.coralDark }}>10초</b>짜리로 시작할게요.
        </AvaSays>
        <Card pad={22} style={{ position: 'relative', overflow: 'hidden' }}>
          <div style={{ fontSize: 12, fontWeight: 800, color: T.coral, letterSpacing: 1.2 }}>FIRST QUEST</div>
          <div style={{ fontSize: 28, fontWeight: 800, color: T.ink, letterSpacing: -0.6, margin: '8px 0 4px' }}>어깨 리셋 10초</div>
          <div style={{ fontSize: 15, color: T.ink2, marginBottom: 18 }}>굳은 목·어깨를 가볍게 풀어요</div>
          <MetaTags tags={[{ icon: 'clock', label: '10초' }, { icon: 'seat', label: '앉아서 가능' }, { icon: 'camera_off', label: '카메라 없음' }]}/>
        </Card>
      </div>
      <FloatCTA hint="통증이 있으면 멈추고 Recovery Quest로 바꿀 수 있어요"><Btn onClick={onStart} icon={<Icon name="play" size={20} color="#fff"/>}>지금 시작</Btn></FloatCTA>
    </Screen>
  );
}

// 5 — First quest player (10s)
function FirstPlayer({ onDone }) {
  return <QuestPlayer title="어깨 리셋" seconds={10} avaLine="부드럽게만 움직이면 돼요. 잘하고 있어요."
    steps={['어깨를 귀 쪽으로 올려요', '뒤로 천천히 크게 돌려요', '숨을 길게 내쉬어요']}
    onDone={onDone} firstRun/>;
}

// 6 — First completion
function FirstDone({ onNext, onHome }) {
  return (
    <CompletionView xp={10} streakDay={1} firstRun
      avaLine="첫 기록이 생겼어요. 오늘은 이것만으로 충분해요."
      primary={{ label: '다음', onClick: onNext }}
      secondary={{ label: '30초 보너스 하기', onClick: onNext }}
    />
  );
}

// 7 — Reminder setup
function Reminder({ onFinish }) {
  const [pick, setPick] = useState(null);
  const opts = [
    { id: 'am', label: '아침에 알려줘', sub: '하루를 가볍게 시작', icon: 'flame' },
    { id: 'noon', label: '점심에 알려줘', sub: '오후 리셋 타이밍', icon: 'bolt' },
    { id: 'pm', label: '저녁에 알려줘', sub: '하루를 정리하며', icon: 'moon' },
    { id: 'later', label: '나중에 설정', sub: '설정에서 언제든 변경', icon: 'gear' },
  ];
  return (
    <Screen bg={T.bg}>
      <div style={{ paddingTop: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}>
          <div style={{ width: 64, height: 64, borderRadius: 20, background: T.coralTint, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="bell" size={30} color={T.coral} sw={2}/>
          </div>
        </div>
        <h1 style={{ fontSize: 25, fontWeight: 800, color: T.ink, letterSpacing: -0.5, lineHeight: 1.3, textAlign: 'center', margin: '0 0 6px' }}>
          내일도 Ava가 10초 Quest를<br/>보내드릴까요?
        </h1>
        <p style={{ fontSize: 15, color: T.ink2, textAlign: 'center', margin: '0 0 24px' }}>매일 같은 시간에 가볍게 알려드려요.</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {opts.map(o => (
            <BigChoice key={o.id} icon={o.icon} label={o.label} sub={o.sub} active={pick === o.id} onClick={() => setPick(o.id)}/>
          ))}
        </div>
      </div>
      <FloatCTA><Btn onClick={onFinish} disabled={!pick}>{pick === 'later' ? '건너뛰고 시작' : '알림 받고 시작'}</Btn></FloatCTA>
    </Screen>
  );
}

Object.assign(window, { FTUE, FloatCTA, BigChoice, Dots });
