/* 실제 앱 화면 갤러리 — 6개 스크롤 카루셀 */

const APP_SCREENS = [
  {key: 'prep', label: '운행 준비', tag: 'STEP 1', desc: '거치대에 스마트폰을 놓고 노선·정류장을 확인합니다.',
    render: () => <PrepScreen />},
  {key: 'home', label: '오늘의 운행', tag: 'STEP 2', desc: '곧 시작하는 운행이 카운트다운으로 안내됩니다.',
    render: () => <HomeScreen />},
  {key: 'recognize', label: '다인 동시 인식', tag: 'LIVE · 0.9초', desc: '여러 명이 동시에 탑승해도 한 번에 매칭합니다.',
    render: () => <RecognitionScreen />},
  {key: 'completed', label: '잔류 확인', tag: '안전 절차', desc: '운행 종료 시 차량 내부를 자동 촬영해 안전을 증빙합니다.',
    render: () => <CompletedScreen />},
  {key: 'detail', label: '운행 상세 · 리포트', tag: '자동 기록', desc: '진출입 시각·거리·인원·잔류 사진까지 한 화면에.',
    render: () => <DriveDetailScreen />},
  {key: 'stats', label: '주간 통계', tag: '대시보드', desc: '이번 주 탑승객·노선별 차트가 자동 생성됩니다.',
    render: () => <StatsScreen />},
];

const SectionGallery = () => {
  const trackRef = React.useRef(null);
  const [activeIdx, setActiveIdx] = React.useState(0);

  const scrollTo = (i) => {
    const track = trackRef.current;
    if (!track) return;
    const cards = track.querySelectorAll('.gallery-card');
    if (cards[i]) {
      track.scrollTo({left: cards[i].offsetLeft - track.offsetLeft - 24, behavior: 'smooth'});
    }
  };

  // update active on scroll
  React.useEffect(() => {
    const track = trackRef.current;
    if (!track) return;
    const onScroll = () => {
      const cards = [...track.querySelectorAll('.gallery-card')];
      const center = track.scrollLeft + track.clientWidth / 2;
      let nearest = 0;
      let best = Infinity;
      cards.forEach((c, i) => {
        const mid = c.offsetLeft - track.offsetLeft + c.offsetWidth / 2;
        const d = Math.abs(mid - center);
        if (d < best) { best = d; nearest = i; }
      });
      setActiveIdx(nearest);
    };
    track.addEventListener('scroll', onScroll, {passive: true});
    onScroll();
    return () => track.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <section id="gallery" className="bg-soft" style={{paddingBottom: 120, overflow: 'hidden'}}>
      <div className="shell">
        <div className="section-head" style={{
          display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'end', gap: 32,
        }}>
          <div>
            <div className="eyebrow"><span className="dot" />REAL APP SCREENS</div>
            <h2 className="section-title" style={{marginTop: 16}}>주요 화면 구성.</h2>
            <p className="section-sub">운수사·고객사·운전자가 운영 현장에서 사용하는 6개 핵심 화면입니다.</p>
          </div>
          <div style={{display: 'flex', gap: 8}}>
            <button type="button" className="gallery-arrow" aria-label="이전 화면"
              onClick={() => scrollTo(Math.max(0, activeIdx - 1))}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6" /></svg>
            </button>
            <button type="button" className="gallery-arrow" aria-label="다음 화면"
              onClick={() => scrollTo(Math.min(APP_SCREENS.length - 1, activeIdx + 1))}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6" /></svg>
            </button>
          </div>
        </div>
      </div>

      <div ref={trackRef} className="gallery-track">
        <div style={{minWidth: 'max(32px, calc((100vw - var(--site-shell-max)) / 2 + 32px))'}} aria-hidden />
        {APP_SCREENS.map((s, i) => (
          <div key={s.key} className={`gallery-card ${i === activeIdx ? 'is-active' : ''}`}>
            <div className="gallery-phone-wrap">
              <div className="gallery-phone">
                <Phone>{s.render()}</Phone>
              </div>
            </div>
            <div className="gallery-caption">
              <div className="chip" style={{marginBottom: 12}}>{s.tag}</div>
              <div style={{fontSize: 18, fontWeight: 800, color: 'var(--sid-ink)', letterSpacing: '-0.02em', marginBottom: 6}}>
                {String(i + 1).padStart(2, '0')}. {s.label}
              </div>
              <div style={{fontSize: 13, color: 'var(--sid-fg-mid)', lineHeight: 1.6, maxWidth: 280}}>{s.desc}</div>
            </div>
          </div>
        ))}
        <div style={{minWidth: 'max(32px, calc((100vw - var(--site-shell-max)) / 2 + 32px))'}} aria-hidden />
      </div>

      {/* dots */}
      <div className="shell" style={{marginTop: 32, display: 'flex', justifyContent: 'center', gap: 8}}>
        {APP_SCREENS.map((_, i) => (
          <button key={i} type="button" aria-label={`${i + 1}번 화면`} onClick={() => scrollTo(i)}
            style={{
              width: i === activeIdx ? 24 : 8, height: 8, borderRadius: 4,
              background: i === activeIdx ? 'var(--sid-blue)' : 'var(--sid-line)',
              border: 'none', cursor: 'pointer', padding: 0,
              transition: 'all 200ms ease',
            }} />
        ))}
      </div>

      <style>{`
        .gallery-track {
          display: flex;
          gap: 28px;
          overflow-x: auto;
          scroll-snap-type: x mandatory;
          padding: 16px 0 8px;
          scrollbar-width: none;
        }
        .gallery-track::-webkit-scrollbar { display: none; }
        .gallery-card {
          flex: 0 0 auto;
          width: 300px;
          scroll-snap-align: center;
          opacity: 0.55;
          transform: scale(0.92);
          transition: opacity 240ms ease, transform 240ms ease;
        }
        .gallery-card.is-active { opacity: 1; transform: scale(1); }
        .gallery-phone-wrap {
          height: 580px;
          display: flex;
          justify-content: center;
          align-items: flex-start;
        }
        .gallery-phone {
          transform: scale(0.62);
          transform-origin: top center;
        }
        .gallery-caption {
          padding: 0 12px;
          text-align: left;
        }
        .gallery-arrow {
          width: 44px; height: 44px;
          border-radius: 50%;
          background: #fff;
          border: 1px solid var(--sid-line);
          color: var(--sid-ink);
          display: grid; place-items: center;
          cursor: pointer;
          transition: border-color 120ms ease, color 120ms ease, background 120ms ease;
        }
        .gallery-arrow:hover {
          border-color: var(--sid-blue);
          color: var(--sid-blue);
        }
      `}</style>
    </section>
  );
};

Object.assign(window, {SectionGallery});
