// home.jsx — Home screen with state variants
const { useState: useStateH } = React;

function HomeHeader({ data, go }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, paddingTop: 6, marginBottom: 16 }}>
      <button onClick={() => go('profile')} style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', padding: 0 }}>
        <div style={{ width: 40, height: 40, borderRadius: 13, background: `linear-gradient(135deg, ${T.coral}, ${T.violet})`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 800, fontSize: 17, boxShadow: `0 3px 0 ${T.coralDark}` }}>{data.initial || '지'}</div>
      </button>
      <div style={{ flex: 1 }}/>
      <StatPill tone="amber" icon={<Icon name="flame" size={18} color={T.amber} fill={T.amber} sw={0}/>} label={data.streak}/>
      <EnergyPill energy={data.energy} max={data.maxEnergy} pro={data.pro} nextSec={data.nextSec} onClick={() => go('energy')}/>
    </div>
  );
}

function QuickActions({ go }) {
  const acts = [
    { id: 'notime', label: '시간 없음', icon: 'clock' },
    { id: 'tired', label: '피곤해요', icon: 'moon' },
    { id: 'nospace', label: '공간 없음', icon: 'seat' },
    { id: 'swap', label: 'Quest 바꾸기', icon: 'quest' },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
      {acts.map(a => (
        <button key={a.id} onClick={() => go('flow', { flow: a.id })} style={{
          display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderRadius: 16,
          background: T.bg, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
          boxShadow: `inset 0 0 0 1.5px ${T.line}`,
        }}>
          <Icon name={a.icon} size={20} color={T.ink2} sw={2}/>
          <span style={{ fontSize: 14.5, fontWeight: 700, color: T.ink, letterSpacing: -0.3 }}>{a.label}</span>
        </button>
      ))}
    </div>
  );
}

function AcademyTeaser({ go }) {
  return (
    <Card pad={18} onClick={() => go('academy')} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 14 }}>
      <div style={{ width: 52, height: 52, borderRadius: 15, background: T.calmSoft, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name="academy" size={26} color={T.calm}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 11.5, fontWeight: 800, color: T.calm, letterSpacing: 0.6 }}>오늘의 운동 배우기</div>
        <div style={{ fontSize: 16.5, fontWeight: 800, color: T.ink, letterSpacing: -0.3, marginTop: 2 }}>스쿼트 자세 만들기</div>
      </div>
      <Icon name="chevron" size={20} color={T.ink3} sw={2.2}/>
    </Card>
  );
}

function Home({ data, go, startQuest }) {
  const v = data.homeVariant || 'default';

  // big quest card per variant
  const variants = {
    default: {
      ava: <>오늘은 오래 앉아 있었어요. <b style={{ color: T.coralDark }}>30초</b>만 어깨를 풀고 시작해요.</>,
      tag: "TODAY'S QUEST", title: '어깨 리셋 30초', desc: '목·어깨 긴장 완화', tone: T.coral,
      meta: [{ icon: 'clock', label: '30초' }, { icon: 'seat', label: '앉아서 가능' }, { icon: 'camera_off', label: '카메라 없음' }],
      primary: { label: '지금 30초 시작', onClick: () => startQuest({ title: '어깨 리셋', seconds: 30, steps: ['어깨를 귀 쪽으로 올려요', '뒤로 천천히 크게 돌려요', '숨을 길게 내쉬어요'], avaLine: '속도보다 부드러움이 중요해요', xp: 10 }, true) },
      secondary: { label: '10초만 할래요', onClick: () => startQuest({ title: '어깨 리셋', seconds: 10, steps: ['어깨를 올려요', '뒤로 돌려요', '숨을 내쉬어요'], avaLine: '짧아도 충분해요', xp: 5 }, true) },
    },
    streakRisk: {
      ava: <>오늘 기록이 아직 비어 있어요. <b style={{ color: T.amberDark }}>10초</b> Recovery로 Streak를 지킬 수 있어요.</>,
      tag: 'STREAK SAVE QUEST', title: '누워서 호흡 10초', desc: '오늘의 연결을 지켜요', tone: T.calm,
      meta: [{ icon: 'clock', label: '10초' }, { icon: 'moon', label: '침대에서' }, { icon: 'wind', label: '회복 모드' }],
      primary: { label: 'Streak 지키기', onClick: () => startQuest({ title: '회복 호흡', seconds: 10, tone: T.calm, steps: ['편하게 누워요', '천천히 들이마셔요', '길게 내쉬어요'], avaLine: '완벽한 운동은 필요 없어요', xp: 5 }, true), variant: 'calm' },
      secondary: { label: '오늘은 쉴래요', onClick: () => go('flow', { flow: 'skip' }) },
    },
    completed: {
      ava: <>오늘 Quest 완료했어요. 원하면 <b style={{ color: T.coralDark }}>1분 보너스</b>로 XP를 더 받을 수 있어요.</>,
      tag: 'COMPLETED TODAY', title: '어깨 리셋 30초', desc: '+10 XP · Streak 유지', tone: T.good, done: true,
      meta: [],
      primary: { label: '1분 보너스 Quest', onClick: () => startQuest({ title: '전신 깨우기', seconds: 60, steps: ['팔을 크게 돌려요', '가볍게 스쿼트해요', '깊게 호흡해요'], avaLine: '여유가 있다면 조금만 더', xp: 20 }) },
      secondary: { label: 'Progress 보기', onClick: () => go('progress') },
    },
    return7: {
      ava: <>다시 온 것만으로 충분해요. 오늘은 <b style={{ color: T.coralDark }}>10초</b>로 재시작해요.</>,
      tag: 'RESTART QUEST', title: '목 긴장 풀기 10초', desc: '7일 만의 복귀를 환영해요', tone: T.coral,
      meta: [{ icon: 'clock', label: '10초' }, { icon: 'seat', label: '앉아서' }, { icon: 'camera_off', label: '카메라 없음' }],
      primary: { label: '다시 시작', onClick: () => startQuest({ title: '목 긴장 풀기', seconds: 10, steps: ['목을 좌우로 기울여요', '천천히 돌려요', '숨을 내쉬어요'], avaLine: '돌아온 게 가장 중요해요', xp: 10 }, true) },
      secondary: null,
    },
  };
  if (data.todayQuest) {
    const q = data.todayQuest;
    const sec = q.seconds || 30;
    variants.default = {
      ava: <>Ava가 오늘 가능한 <b style={{ color: T.coralDark }}>{sec}초</b> 건강 행동을 골랐어요.</>,
      tag: "TODAY'S QUEST", title: q.title, desc: q.meta || '오늘의 건강 행동', tone: q.tone || T.coral,
      meta: [{ icon: 'clock', label: `${sec}초` }, { icon: q.icon || 'seat', label: q.meta || '바로 가능' }, { icon: 'camera_off', label: '카메라 없음' }],
      primary: { label: `지금 ${sec}초 시작`, onClick: () => startQuest(q, true) },
      secondary: { label: '더 쉬운 Quest', onClick: () => go('flow', { flow: 'swap' }) },
    };
    variants.completed = {
      ...variants.completed,
      title: q.title,
      desc: `+${q.xp || 10} XP · Streak 유지`,
    };
  }
  const c = variants[v];

  return (
    <Screen bg={T.surface} nav="home">
      <HomeHeader data={data} go={go}/>
      <AvaSays size={46} style={{ marginBottom: 16 }}>{c.ava}</AvaSays>

      {/* big quest card */}
      <Card pad={22} style={{ marginBottom: 16, position: 'relative', overflow: 'hidden', boxShadow: c.done ? `0 10px 30px ${T.good}1c` : `0 12px 34px ${c.tone}22, inset 0 0 0 2px ${c.tone === T.calm ? T.calm : c.tone === T.good ? 'transparent' : T.coral}` }}>
        {c.done && <div style={{ position: 'absolute', top: 18, right: 18, width: 40, height: 40, borderRadius: 999, background: T.good, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={22} color="#fff" sw={2.6}/></div>}
        <div style={{ fontSize: 12, fontWeight: 800, color: c.tone === T.good ? T.good : c.tone === T.calm ? T.calm : T.coral, letterSpacing: 1.2 }}>{c.tag}</div>
        <div style={{ fontSize: 27, fontWeight: 800, color: T.ink, letterSpacing: -0.6, margin: '8px 0 4px' }}>{c.title}</div>
        <div style={{ fontSize: 15, color: T.ink2, marginBottom: c.meta.length ? 18 : 18 }}>{c.desc}</div>
        {c.meta.length > 0 && <div style={{ marginBottom: 20 }}><MetaTags tags={c.meta}/></div>}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <Btn variant={c.primary.variant || (c.tone === T.good ? 'dark' : 'primary')} onClick={c.primary.onClick} icon={!c.done ? <Icon name="play" size={19} color="#fff"/> : null}>{c.primary.label}</Btn>
          {c.secondary && <Btn variant="soft" size="md" onClick={c.secondary.onClick}>{c.secondary.label}</Btn>}
        </div>
      </Card>

      {/* daily goal */}
      <Card pad={18} style={{ marginBottom: 14, display: 'flex', alignItems: 'center', gap: 16 }}>
        <DailyGoalRing value={data.completedToday ? 1 : 0} goal={1}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12, fontWeight: 800, color: T.amberDark, letterSpacing: 0.4 }}>DAILY GOAL</div>
          <div style={{ fontSize: 17, fontWeight: 800, color: T.ink, letterSpacing: -0.3, margin: '1px 0 8px' }}>{data.completedToday ? '오늘 목표 달성!' : '오늘 1개 Quest'}</div>
          <XPBar value={data.xp} max={200} height={9}/>
          <div style={{ fontSize: 12.5, color: T.ink3, fontWeight: 700, marginTop: 6, fontVariantNumeric: 'tabular-nums' }}>Lv.{data.level} · {data.xp} / 200 XP</div>
        </div>
      </Card>

      {/* streak risk extra info */}
      {v === 'streakRisk' && (
        <Card pad={16} style={{ marginBottom: 14, display: 'flex', alignItems: 'center', gap: 12, background: T.amberSoft }}>
          <Icon name="flame" size={26} color={T.amber}/>
          <div style={{ fontSize: 14, color: T.ink, fontWeight: 600 }}><b>현재 {data.streak}일 연속</b> · 오늘 10초만 하면 유지돼요</div>
        </Card>
      )}

      <div style={{ fontSize: 13, fontWeight: 800, color: T.ink3, letterSpacing: 0.6, margin: '8px 2px 12px' }}>Quick Actions</div>
      <div style={{ marginBottom: 16 }}><QuickActions go={go}/></div>

      <AcademyTeaser go={go}/>
      <div style={{ height: 12 }}/>
      <BodyCheckTeaser go={go}/>
      <div style={{ height: 12 }}/>
    </Screen>
  );
}

function BodyCheckTeaser({ go }) {
  return (
    <Card pad={18} onClick={() => go('bodycheck')} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 14, background: `linear-gradient(150deg, ${T.tealSoft}, ${T.bg})` }}>
      <div style={{ width: 52, height: 52, borderRadius: 15, background: T.teal, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name="scan" size={26} color="#fff" sw={1.9}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 11.5, fontWeight: 800, color: T.tealDark, letterSpacing: 0.6 }}>바디 체크</div>
        <div style={{ fontSize: 16.5, fontWeight: 800, color: T.ink, letterSpacing: -0.3, marginTop: 2 }}>주간 자세 변화 보기</div>
      </div>
      <Icon name="chevron" size={20} color={T.ink3} sw={2.2}/>
    </Card>
  );
}

Object.assign(window, { Home, QuickActions, AcademyTeaser, HomeHeader });
