// programs.jsx — Structured multi-week plans + workout library (Speak-style)
const { useState: useStatePg } = React;

const PROGRAMS = [
  { id: 'posture', cat: 'mobility', title: '자세 교정 4주', sub: '굳은 목·어깨·등을 매일 조금씩', weeks: 4, perWeek: 5, mins: '8분/일', level: '입문', badge: '인기', done: 6, total: 20 },
  { id: 'base', cat: 'strength', title: '체력 기초 4주', sub: '스쿼트·힌지·푸시 기본기', weeks: 4, perWeek: 4, mins: '12분/일', level: '입문', done: 0, total: 16 },
  { id: 'recover', cat: 'recovery', title: '회복 루틴 2주', sub: '피로·수면을 위한 저강도 호흡', weeks: 2, perWeek: 6, mins: '6분/일', level: '누구나', done: 0, total: 12 },
  { id: 'core', cat: 'cardio', title: '코어 강화 4주', sub: '앉아서도 가능한 코어 트레이닝', weeks: 4, perWeek: 4, mins: '10분/일', level: '중급', done: 0, total: 16 },
];

const LIB = [
  { id: 'l1', cat: 'mobility', title: '목·어깨 리셋', mins: '3분', level: '입문', part: '상체' },
  { id: 'l2', cat: 'strength', title: '스쿼트 기본', mins: '6분', level: '입문', part: '하체' },
  { id: 'l3', cat: 'cardio', title: '코어 서킷', mins: '8분', level: '중급', part: '코어' },
  { id: 'l4', cat: 'recovery', title: '수면 전 호흡', mins: '5분', level: '누구나', part: '전신' },
  { id: 'l5', cat: 'strength', title: '힙 힌지 연습', mins: '6분', level: '입문', part: '하체' },
  { id: 'l6', cat: 'mobility', title: '흉추 열기', mins: '4분', level: '중급', part: '상체' },
];

function Programs({ go, data, startQuest }) {
  const [detail, setDetail] = useStatePg(null);
  if (detail) return <ProgramDetail program={detail} back={() => setDetail(null)} startQuest={startQuest}/>;
  return <ProgramsHub go={go} data={data} openDetail={setDetail} startQuest={startQuest}/>;
}

function ProgramsHub({ go, data, openDetail, startQuest }) {
  const [part, setPart] = useStatePg('전체');
  const programs = (data && data.programs && data.programs.length) ? data.programs : PROGRAMS;
  const library = (data && data.exerciseLibrary && data.exerciseLibrary.length) ? data.exerciseLibrary : LIB;
  const active = programs.find(p => p.id === (data.activeProgram || 'posture')) || programs[0];
  const others = programs.filter(p => p.id !== active.id);
  const c = catColor(active.cat);
  const weekNum = Math.min(active.weeks, Math.floor(active.done / active.perWeek) + 1);
  const dayNum = active.done + 1;
  const parts = ['전체', '상체', '하체', '코어', '전신'];
  const lib = library.filter(l => part === '전체' || l.part === part);

  return (
    <Screen bg={T.surface} nav="programs">
      <TopBar title="프로그램"/>

      {/* active program */}
      <div style={{ fontSize: 13, fontWeight: 800, color: T.ink3, letterSpacing: 0.4, margin: '0 2px 10px' }}>진행 중</div>
      <Card pad={0} onClick={() => openDetail(active)} style={{ marginBottom: 22, overflow: 'hidden', cursor: 'pointer' }}>
        <div style={{ padding: '18px 18px 16px', background: `linear-gradient(135deg, ${c.c}, ${c.d})`, color: onColor(c.c) }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ fontSize: 11.5, fontWeight: 800, color: onColor(c.c), opacity: 0.85, letterSpacing: 0.6 }}>{weekNum}주차 / {active.weeks} · {active.level}</div>
            <div style={{ fontSize: 12, fontWeight: 700, color: onColor(c.c), opacity: 0.9 }}>{active.done}/{active.total} 세션</div>
          </div>
          <div style={{ fontSize: 23, fontWeight: 800, color: onColor(c.c), letterSpacing: -0.4, margin: '6px 0 14px' }}>{active.title}</div>
          <div style={{ height: 7, borderRadius: 999, background: onColor(c.c) === '#fff' ? 'rgba(255,255,255,0.28)' : 'rgba(0,0,0,0.18)', overflow: 'hidden' }}>
            <div style={{ width: `${active.done / active.total * 100}%`, height: '100%', borderRadius: 999, background: onColor(c.c) }}/>
          </div>
        </div>
        <div style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 800, color: T.ink }}>오늘 · Day {dayNum} — {active.title.replace(/ \d+주$/, '')} 세션</div>
            <div style={{ fontSize: 13, color: T.ink3, fontWeight: 600 }}>{active.mins} · 카메라 자세 체크</div>
          </div>
          <button onClick={(e) => { e.stopPropagation(); startQuest({ title: active.title + ' 세션', seconds: 60, tone: c.c, steps: ['워밍업으로 시작', '천천히 호흡', '무리하지 않기'], avaLine: '오늘 세션이에요', xp: 20 }); }} style={{ flexShrink: 0, display: 'flex', alignItems: 'center', gap: 6, background: c.c, color: '#fff', border: 'none', borderRadius: 12, padding: '11px 16px', fontSize: 14.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>
            <Icon name="play" size={15} color="#fff"/>{active.done > 0 ? '이어서' : '시작'}
          </button>
        </div>
      </Card>

      {/* recommended programs */}
      <div style={{ fontSize: 13, fontWeight: 800, color: T.ink3, letterSpacing: 0.4, margin: '0 2px 10px' }}>추천 프로그램</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 24 }}>
        {others.map(p => {
          const pc = catColor(p.cat);
          return (
            <button key={p.id} onClick={() => openDetail(p)} style={{ display: 'flex', alignItems: 'center', gap: 14, width: '100%', textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit', background: T.bg, border: 'none', borderRadius: 18, padding: 14, boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
              <div style={{ width: 54, height: 54, borderRadius: 15, background: pc.s, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name={p.cat === 'strength' ? 'dumbbell' : p.cat === 'recovery' ? 'leaf' : 'bolt'} size={26} color={pc.c} fill={p.cat === 'cardio' ? pc.c : 'none'} sw={2}/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <span style={{ fontSize: 16, fontWeight: 800, color: T.ink, letterSpacing: -0.3 }}>{p.title}</span>
                  {p.badge && <span style={{ fontSize: 9.5, fontWeight: 800, color: pc.c, background: pc.s, padding: '2px 6px', borderRadius: 6, letterSpacing: 0.5 }}>{p.badge}</span>}
                </div>
                <div style={{ fontSize: 13, color: T.ink3, fontWeight: 600, marginTop: 1 }}>{p.sub}</div>
                <div style={{ fontSize: 12, color: T.ink3, fontWeight: 600, marginTop: 4 }}>{p.weeks}주 · 주 {p.perWeek}회 · {p.mins} · {p.level}</div>
              </div>
              <Icon name="chevron" size={20} color={T.ink3} sw={2.2}/>
            </button>
          );
        })}
      </div>

      {/* library */}
      <div style={{ fontSize: 13, fontWeight: 800, color: T.ink3, letterSpacing: 0.4, margin: '0 2px 10px' }}>라이브러리</div>
      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 10, marginRight: -22 }}>
        {parts.map(p => (
          <button key={p} onClick={() => setPart(p)} style={{ whiteSpace: 'nowrap', flexShrink: 0, padding: '9px 16px', borderRadius: 999, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14, fontWeight: 700, border: 'none', background: part === p ? T.coral : T.bg, color: part === p ? '#fff' : T.ink2, boxShadow: part === p ? 'none' : `inset 0 0 0 1.5px ${T.line2}` }}>{p}</button>
        ))}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 4 }}>
        {lib.map(l => {
          const lc = catColor(l.cat);
          return (
            <button key={l.id} onClick={() => startQuest(l.quest || { title: l.title, seconds: 60, tone: lc.c, steps: ['천천히 시작해요', '호흡에 집중', '무리하지 않기'], avaLine: '좋은 선택이에요', xp: 16 })} style={{ display: 'flex', alignItems: 'center', gap: 13, width: '100%', textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit', background: T.bg, border: 'none', borderRadius: 16, padding: 13, boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
              <div style={{ width: 44, height: 44, borderRadius: 12, background: lc.s, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name="play" size={20} color={lc.c}/>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15.5, fontWeight: 700, color: T.ink, letterSpacing: -0.2 }}>{l.title}</div>
                <div style={{ fontSize: 12.5, color: T.ink3, fontWeight: 600 }}>{l.part} · {l.mins} · {l.level}</div>
              </div>
              <Icon name="chevron" size={18} color={T.ink3} sw={2.2}/>
            </button>
          );
        })}
      </div>
      <div style={{ height: 16 }}/>
    </Screen>
  );
}

function ProgramDetail({ program, back, startQuest }) {
  const c = catColor(program.cat);
  const [openWeek, setOpenWeek] = useStatePg(1);
  const sessions = (program.sessions && program.sessions.length ? program.sessions.map(s => s.title) : ['워밍업 모빌리티', '코어 액티베이션', '메인 세트 A', '메인 세트 B', '쿨다운 호흡', '회복 스트레칭']);
  return (
    <Screen bg={T.surface} pad={false}>
      {/* hero */}
      <div style={{ padding: '8px 22px 22px', background: `linear-gradient(135deg, ${c.c}, ${c.d})`, color: onColor(c.c) }}>
        <button onClick={back} style={{ width: 40, height: 40, borderRadius: 999, border: 'none', cursor: 'pointer', background: onColor(c.c) === '#fff' ? 'rgba(255,255,255,0.22)' : 'rgba(0,0,0,0.14)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
          <Icon name="back" size={22} color={onColor(c.c)} sw={2.2}/>
        </button>
        <div style={{ fontSize: 11.5, fontWeight: 800, color: onColor(c.c), opacity: 0.85, letterSpacing: 0.6 }}>{program.weeks}주 프로그램 · {program.level}</div>
        <div style={{ fontSize: 27, fontWeight: 800, color: onColor(c.c), letterSpacing: -0.5, margin: '6px 0 6px' }}>{program.title}</div>
        <div style={{ fontSize: 14.5, color: onColor(c.c), opacity: 0.92, fontWeight: 500 }}>{program.sub}</div>
        <div style={{ display: 'flex', gap: 18, marginTop: 16 }}>
          {[[`${program.perWeek}회`, '주간'], [program.mins.replace('/일', ''), '하루'], [`${program.total}`, '세션']].map((s, i) => (
            <div key={i}><div style={{ fontSize: 18, fontWeight: 800, color: onColor(c.c) }}>{s[0]}</div><div style={{ fontSize: 11.5, color: onColor(c.c), opacity: 0.8, fontWeight: 600 }}>{s[1]}</div></div>
          ))}
        </div>
      </div>

      <div style={{ padding: '18px 22px 0' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 11, background: T.bg, borderRadius: 16, padding: 14, marginBottom: 18, boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
          <AvaOrb size={34}/>
          <div style={{ fontSize: 14, color: T.ink, fontWeight: 500, lineHeight: 1.5 }}>매일 같은 시간에 짧게 이어가면 4주 뒤 확실히 달라져요. 무리한 날은 회복 세션으로 바꿔도 돼요.</div>
        </div>

        {/* weeks accordion */}
        {Array.from({ length: program.weeks }).map((_, wi) => {
          const week = wi + 1, open = openWeek === week, locked = week > 2;
          return (
            <div key={wi} style={{ marginBottom: 10, background: T.bg, borderRadius: 16, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
              <button onClick={() => setOpenWeek(open ? 0 : week)} style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit', background: 'none', border: 'none', padding: 16 }}>
                <div style={{ width: 34, height: 34, borderRadius: 10, background: locked ? T.surface2 : c.s, color: locked ? T.ink3 : c.c, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 800, flexShrink: 0 }}>{locked ? <Icon name="lock" size={15} color={T.ink3} sw={2}/> : week}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15.5, fontWeight: 800, color: locked ? T.ink3 : T.ink }}>Week {week}</div>
                  <div style={{ fontSize: 12.5, color: T.ink3, fontWeight: 600 }}>{locked ? '이전 주 완료 후 잠금 해제' : `${program.perWeek}개 세션`}</div>
                </div>
                {!locked && <Icon name="chevron" size={18} color={T.ink3} sw={2.2} style={{ transform: open ? 'rotate(90deg)' : 'none', transition: 'transform .2s' }}/>}
              </button>
              {open && !locked && (
                <div style={{ padding: '0 16px 12px' }}>
                  {sessions.slice(0, program.perWeek).map((s, si) => {
                    const sdone = week === 1 || (week === 2 && si < 2);
                    return (
                      <div key={si} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 0', borderTop: `0.5px solid ${T.line}` }}>
                        <div style={{ width: 26, height: 26, borderRadius: 999, background: sdone ? T.good : T.surface2, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                          {sdone ? <Icon name="check" size={14} color="#fff" sw={2.8}/> : <span style={{ fontSize: 12, fontWeight: 800, color: T.ink3 }}>{si + 1}</span>}
                        </div>
                        <div style={{ flex: 1, fontSize: 14.5, fontWeight: 600, color: sdone ? T.ink3 : T.ink }}>Day {si + 1} · {s}</div>
                        {!sdone && <Icon name="play" size={16} color={c.c}/>}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
        <div style={{ height: 16 }}/>
      </div>

      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '14px 22px 30px', background: `linear-gradient(transparent, ${T.surface} 30%)` }}>
        <Btn onClick={() => startQuest((program.sessions && program.sessions.find(s => s)) || { title: program.title + ' 세션', seconds: 60, tone: c.c, steps: ['워밍업으로 시작', '천천히 호흡', '무리하지 않기'], avaLine: '오늘 세션을 시작해요', xp: 20 })} icon={<Icon name="play" size={18} color="#fff"/>}>{program.done > 0 ? '이어서 하기' : '프로그램 시작'}</Btn>
      </div>
    </Screen>
  );
}

Object.assign(window, { Programs });
