/* 모모, 테리 — Family (확장수업) + About screens */

function FamilyScreen({ go }) {
  const STEPS = Array.from({ length: 12 }, (_, i) => (i + 1) + '호');
  const [step, setStep] = React.useState('1호');
  const stepListRef = React.useRef(null);
  const scrollStepIntoView = (s) => {
    const list = stepListRef.current;
    if (!list) return;
    const btn = list.querySelector('[data-step="' + s + '"]');
    if (!btn) return;
    const listRect = list.getBoundingClientRect();
    const btnRect = btn.getBoundingClientRect();
    if (btnRect.left < listRect.left) {
      list.scrollLeft -= (listRect.left - btnRect.left) + 20;
    } else if (btnRect.right > listRect.right) {
      list.scrollLeft += (btnRect.right - listRect.right) + 20;
    }
  };

  const [week, setWeek] = React.useState('1주차');

  const [content, setContent] = React.useState(undefined); // undefined = loading, null = none found
  const [extras, setExtras] = React.useState({ family: [], videos: [] });

  React.useEffect(() => {
    let cancelled = false;
    setContent(undefined);
    setExtras({ family: [], videos: [] });
    fetchContentByStep(step).then(async (c) => {
      if (cancelled) return;
      setContent(c);
      if (c) {
        const ex = await fetchFamilyExtras(c.id);
        if (!cancelled) setExtras(ex);
      }
    });
    return () => { cancelled = true; };
  }, [step]);

  return (
    <main>
      <div className="page-banner">
        <div className="wrap">
          <div className="crumb">홈 · 확장수업</div>
          <h1>집에서 이어가는 확장수업 자료</h1>
          <p>그림책, 노래율동, 주간 오디오로 우리 아이와 함께해요.</p>
        </div>
      </div>

      <section>
        <div className="wrap">
          {/* STEP list */}
          <div className="step-list-wrap">
            <button className="step-arrow left" onClick={() => {
              const idx = STEPS.indexOf(step);
              const next = STEPS[Math.max(0, idx - 1)];
              setStep(next);
              scrollStepIntoView(next);
            }} aria-label="이전">
              <Arrow style={{ transform: 'rotate(180deg)' }} />
            </button>
            <div className="step-list" ref={stepListRef}>
              {STEPS.map((s) => (
                <button key={s} data-step={s} className={'step-item' + (step === s ? ' active' : '')} onClick={() => { setStep(s); scrollStepIntoView(s); }}>{s}</button>
              ))}
            </div>
            <button className="step-arrow right" onClick={() => {
              const idx = STEPS.indexOf(step);
              const next = STEPS[Math.min(STEPS.length - 1, idx + 1)];
              setStep(next);
              scrollStepIntoView(next);
            }} aria-label="다음">
              <Arrow />
            </button>
          </div>

          {/* week tabs */}
          <div className="week-tabs">
            {['1주차', '2주차', '3주차', '4주차'].map((w) => (
              <button key={w} className={'chip' + (week === w ? ' active' : '')} onClick={() => setWeek(w)}>{w}</button>
            ))}
          </div>

          <div className="sec-head" style={{ marginBottom: 28 }}>
            <h2 className="sec-title">{week} 확장수업</h2>
            <p className="sec-sub">{content ? '이번 주 「' + content.topic + '」 주제와 연결된 가정 활동이에요.' : '주제와 연결된 가정 활동이에요.'}</p>
          </div>

          {content === undefined ? (
            <p style={{ textAlign: 'center', color: 'var(--muted)', padding: '40px 0' }}>불러오는 중…</p>
          ) : content === null ? (
            <div style={{ textAlign: 'center', padding: '40px 0' }}>
              <p style={{ color: 'var(--muted)', fontWeight: 700, fontSize: 16 }}>{step}에 등록된 확장수업 자료가 아직 없어요.</p>
              <p style={{ color: 'var(--muted)', fontSize: 13.5, marginTop: 8 }}>관리자 페이지에서 콘텐츠를 등록하고 공개해 보세요.</p>
            </div>
          ) : (
            <React.Fragment>
              {/* 3 column grid */}
              <div className="family-grid">
                {extras.family.map((f, i) => {
                  const p = PASTELS[(f.pastel || 0) % PASTELS.length];
                  return (
                    <div className="fam-col" key={i}>
                      <div className="fam-label">{f.label}</div>
                      <article className="card card-hover fam-card">
                        <div className="fam-thumb" style={{ background: p.bg, color: p.fg }}>
                          <span className="badge">{f.kind} · {f.vol}</span>
                          <h4 style={{ whiteSpace: 'pre-line' }}>{f.title}</h4>
                          <Ph label="콘텐츠 일러스트" style={{ position: 'absolute', right: 16, top: 54, width: 92, height: 92, borderRadius: 18, background: 'rgba(255,255,255,.45)' }} />
                          <button className="play"><PlayIcon/></button>
                        </div>
                        <div className="fam-foot">
                          <b>{f.title.replace('\n', ' ')}</b>
                          <small>{f.sub}</small>
                        </div>
                      </article>
                    </div>
                  );
                })}
              </div>

              {/* recommended videos */}
              <div className="sec-head" style={{ margin: '54px 0 24px' }}>
                <div className="sec-eyebrow">추천 영상</div>
                <h2 className="sec-title">함께 보면 좋아요</h2>
              </div>
              <div className="video-row" style={{ marginTop: 0 }}>
                {extras.videos.map((v, i) => {
                  const p = PASTELS[(v.pastel || 0) % PASTELS.length];
                  return (
                    <article className="card card-hover video-card" key={i}>
                      <div className="v-thumb" style={{ background: p.bg }}>
                        <span className="badge badge-solid v-tag">{v.tag}</span>
                        <Ph label="영상 썸네일" style={{ position: 'absolute', inset: 0, background: 'transparent' }} />
                        <button className="play"><PlayIcon/></button>
                      </div>
                      <div className="v-foot">
                        <b>{v.title}</b>
                        <small>{v.sub}</small>
                      </div>
                    </article>
                  );
                })}
              </div>
            </React.Fragment>
          )}
        </div>
      </section>
    </main>
  );
}

function AboutScreen({ go }) {
  return (
    <main>
      <div className="page-banner">
        <div className="wrap">
          <div className="crumb">홈 · 모모테리 소개</div>
          <h1>모모와 테리를 소개합니다</h1>
          <p>아이의 하루에 따뜻한 친구가 되어주는 두 캐릭터예요.</p>
        </div>
      </div>

      <section>
        <div className="wrap" style={{ maxWidth: 820 }}>
          <div className="cat-grid" style={{ gridTemplateColumns: '1fr 1fr' }}>
            {['모모', '테리'].map((who) => {
              const c = CHARS[who];
              return (
                <div className="card" key={who} style={{ padding: '32px 30px', textAlign: 'center' }}>
                  <Char who={who} size={120} style={{ margin: '0 auto 18px', borderWidth: 3 }} />
                  <h3 style={{ fontSize: 24 }}>{who} <span style={{ color: c.color, fontSize: 16 }}>{c.en}</span></h3>
                  <div className="badge" style={{ margin: '10px 0 4px', background: 'color-mix(in srgb, ' + c.color + ' 16%, #fff)', color: c.color }}>{c.age} · {c.tag}</div>
                  <p style={{ color: 'var(--muted)', marginTop: 10 }}>{c.desc}</p>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'center', marginTop: 14 }}>
                    {c.keywords.map((k) => (
                      <span key={k} style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--muted)', background: 'var(--primary-tint-2)', padding: '4px 10px', borderRadius: 999 }}>{k}</span>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>

          <div className="goal-box" style={{ marginTop: 30 }}>
            <span className="goal-title">🌱 모모테리가 만드는 콘텐츠</span>
            <ul>
              <li>1~2세 발달 6개 영역을 균형 있게 담은 주제별 통합 수업자료</li>
              <li>교사가 바로 쓰는 지도서와 활동지, 그리고 차시별 수업 흐름</li>
              <li>집에서 이어가는 그림책·노래율동·주간 오디오 확장수업 자료</li>
            </ul>
          </div>

          <div style={{ textAlign: 'center', marginTop: 36 }}>
            <button className="btn btn-primary" onClick={() => go('materials')}>수업자료 둘러보기 <Arrow/></button>
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { FamilyScreen, AboutScreen });
