// 모원렌탈 랜딩 — 섹션 컴포넌트 (hooks.jsx, icons.jsx 선행 로드)
// Expects: window.I, window.ProductArt, window.HeroVisual, window.cardDesigns,
//          window.useCountUp, window.useInView

const { useState, useEffect, useRef } = React;

const LOGO_SRC = 'logo.png';
const MAIN_PHONE = '1844-1735';
const MAIN_PHONE_HREF = 'tel:1844-1735';

/* ---------- Product image (원격/로컬 URL + 로드 실패 시 SVG) ---------- */
function ProductThumb({ variant, image, name }) {
  const [broken, setBroken] = useState(false);
  return (
    <div className="product__thumb-layer">
      {broken || !image ? (
        <ProductArt variant={variant} />
      ) : (
        <img
          className="product__photo"
          src={image}
          alt={name}
          loading="lazy"
          decoding="async"
          onError={() => setBroken(true)}
        />
      )}
    </div>
  );
}

const GIFT_IMG_BASE = 'images/사은품/';
const GIFT_NEW_IMG_BASE = 'images/사은품-NEW/';

/* ---------- 사은품 이미지 (폴더명 = images/사은품/하위 디렉터리) ---------- */
function GiftThumb({ folder, label, icon }) {
  const [broken, setBroken] = useState(false);
  const src = GIFT_IMG_BASE + folder + '/1.png';
  if (broken) {
    return <div className="gift__icon-fallback">{icon}</div>;
  }
  return (
    <img
      className="gift__photo"
      src={src}
      alt={label}
      loading="lazy"
      decoding="async"
      onError={() => setBroken(true)}
    />
  );
}

/* ---------- 신형 사은품 이미지 (파일명 직접 매칭) ---------- */
function GiftNewThumb({ fileName, label, icon }) {
  const [broken, setBroken] = useState(false);
  const src = encodeURI(GIFT_NEW_IMG_BASE + fileName);
  if (broken) return <div className="gift__icon-fallback">{icon}</div>;
  return (
    <img
      className="gift__photo"
      src={src}
      alt={label}
      loading="lazy"
      decoding="async"
      onError={() => setBroken(true)}
    />
  );
}

/* ---------- 실시간 방문자 느낌 (스크롤 후 표시) ---------- */
function LiveViewingBar({ hasStickyCta }) {
  const [visible, setVisible] = useState(false);
  const [count, setCount] = useState(() => 28 + Math.floor(Math.random() * 52));
  const [label, setLabel] = useState('인기 렌탈 제품');

  useEffect(() => {
    const onScroll = () => {
      if (window.scrollY > 140) setVisible(true);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    if (!visible) return;
    let t;
    const bump = () => {
      setCount((c) => {
        const delta = Math.floor(Math.random() * 9) - 3;
        return Math.min(198, Math.max(9, c + delta));
      });
      t = setTimeout(bump, 2200 + Math.floor(Math.random() * 4200));
    };
    bump();
    return () => clearTimeout(t);
  }, [visible]);

  useEffect(() => {
    if (!visible) return;
    const cat = window.PRODUCT_CATALOG;
    if (!cat || !cat.length) return;
    let t;
    const pick = () => {
      const p = cat[Math.floor(Math.random() * cat.length)];
      setLabel(p.name);
      t = setTimeout(pick, 4500 + Math.floor(Math.random() * 5500));
    };
    pick();
    return () => clearTimeout(t);
  }, [visible]);

  if (!visible) return null;

  return (
    <div
      className={'live-viewing' + (hasStickyCta ? ' live-viewing--above-sticky' : '')}
      role="status"
      aria-live="polite"
    >
      <span className="live-viewing__pulse" aria-hidden="true"/>
      <span className="live-viewing__text">
        <strong className="live-viewing__num">{count}</strong>
        명이 <span className="live-viewing__product">「{label}」</span> 상세를 보고 있어요
      </span>
    </div>
  );
}

/* ---------- Header ---------- */
function Header({ onApply }) {
  return (
    <header className="site-header">
      <div className="site-header__inner">
        <div className="brand-lockup">
          <img className="brand-lockup__logo" src={LOGO_SRC} alt="모원렌탈" width="160" height="48"/>
          <div>
            <div className="brand-lockup__name">모원렌탈</div>
            <div className="brand-lockup__sub">정수기 렌탈</div>
          </div>
        </div>
        <a href="#apply" className="hdr-cta" onClick={(e)=>{e.preventDefault(); onApply();}}>
          <I.Phone width="14" height="14"/>무료상담
        </a>
      </div>
    </header>
  );
}

/* ---------- Hero ---------- */
function Hero() {
  const decoImages = [
    'images/히어로/a.png',
    'images/히어로/b.png',
    'images/히어로/c.png',
    'images/히어로/d.png',
  ];

  return (
    <section className="hero" data-screen-label="01 Hero">
      <div className="hero__deco" aria-hidden="true">
        {decoImages.map((src, i) => (
          <img
            key={src + i}
            className={`hero__deco-img hero__deco-img--${i + 1}`}
            src={src}
            alt=""
            loading="eager"
            decoding="async"
          />
        ))}
      </div>
      <div className="hero__vignette" aria-hidden="true" />
      <div className="hero__inner">
        <div className="hero__ribbon">
          <span className="dot"></span>
          2026 공식 프로모션 진행중
        </div>
        <div className="hero__kicker">생활의 기준을 채우다</div>
        <h1 className="hero__title">
          <span className="block">최대 지원금</span>부터 <span className="block">사은품까지</span><br/>
          한번에 다 드립니다
        </h1>
        <p className="hero__subtitle">
          전국 최저가 모원렌탈에서 공식 프로모션을<br/>
          가장 합리적인 조건으로 만나보세요.
        </p>
        {/* 모원 정수기 아이콘/일러스트(HeroVisual) — 배경 사진만 쓸 때는 아래 블록을 주석으로 두세요. 다시 쓰려면 주석만 제거하면 됩니다. */}
        {/*
        <div className="hero__visual">
          <HeroVisual/>
        </div>
        */}
        <div className="hero__badges">
          <div className="hero__badge gold">3개월 렌탈료 면제</div>
          <div className="hero__badge">당일설치</div>
          <div className="hero__badge">사은품 증정</div>
        </div>
        <div className="hero__scroll" aria-hidden="true">
          <span className="hero__scroll-text">SCROLL</span>
          <span className="hero__scroll-line"></span>
        </div>
      </div>
    </section>
  );
}

/* ---------- Status (실시간 신청 현황) ---------- */
function Status() {
  const ref = useRef(null);
  const inView = useInView(ref);
  const current = useCountUp(77, inView);
  const remaining = 100 - current;
  const pct = (current / 100) * 100;

  return (
    <section className="section section--subtle" ref={ref}>
      <div className="container">
        <div className="status-card">
          <div className="status-card__eyebrow">프로모션 신청현황</div>
          <h2 className="status-card__title">재고 소진 시 이벤트 종료!</h2>
          <p className="status-card__sub">선착순 100명 한정 특별 혜택</p>

          <div className="counter">
            <span className="counter__current">{current}</span>
            <span className="counter__suffix">명 신청중</span>
          </div>
          <p className="counter__total">
            선착순 <b>100명 한정</b> · 현재까지 {current}명 참여
          </p>
          <div className="progress">
            <div className="progress__bar" style={{ width: `${pct}%` }}></div>
          </div>

          <div className="status-stats">
            <div className="status-stat is-urgent">
              <div className="status-stat__num">{remaining}</div>
              <div className="status-stat__label">남은 자리</div>
            </div>
            <div className="status-stat">
              <div className="status-stat__num status-stat__num--deadline">⏰ 마감임박</div>
              <div className="status-stat__label">오늘 자정까지</div>
            </div>
          </div>

          <div className="status-notes">
            <ul>
              <li>전문상담원이 전화드립니다. 꼭 받아주세요!</li>
              <li>미성년자 및 신용불량자는 신청이 불가합니다.</li>
            </ul>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Notice modal (alert 대체) ---------- */
function NoticeModal({ open, title, message, onClose }) {
  if (!open) return null;
  return (
    <div
      className="modal-backdrop"
      role="dialog"
      aria-modal="true"
      aria-labelledby="notice-modal-title"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button type="button" className="modal__close" onClick={onClose} aria-label="닫기">
          ×
        </button>
        <h2 id="notice-modal-title" className="notice-modal__title">
          {title}
        </h2>
        <div className="notice-modal__body">{message}</div>
        <button type="button" className="submit-btn" style={{ marginTop: 22, width: '100%' }} onClick={onClose}>
          확인
        </button>
      </div>
    </div>
  );
}

/* ---------- Inquiry Form ---------- */
function InquiryForm({ onSubmit, onNotice }) {
  const fallbackProducts = [
    '스위치 무선 정수기','나노직수 미니 정수기','아이콘2 정수기','아이콘3 정수기',
    '아이콘 프로 정수기','미니 얼음정수기','스탠다드 얼음정수기','얼음정수기 RO(지하수)',
    '아이콘 스탠드 정수기','스스로케어 비데','더블케어 비데2','노블 제습공기청정기 10평형',
  ];
  const products = (window.PRODUCT_CATALOG && window.PRODUCT_CATALOG.length
    ? window.PRODUCT_CATALOG.map((p) => p.name)
    : fallbackProducts
  );
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [product, setProduct] = useState('');
  const [agree, setAgree] = useState(false);

  const formatPhone = (v) => {
    const d = v.replace(/\D/g,'').slice(0,11);
    if (d.length < 4) return d;
    if (d.length < 8) return `${d.slice(0,3)}-${d.slice(3)}`;
    return `${d.slice(0,3)}-${d.slice(3,7)}-${d.slice(7)}`;
  };

  const notice = onNotice || (() => {});

  const submit = (e) => {
    e.preventDefault();
    if (!name.trim()) {
      notice('입력 확인', '성명을 입력해주세요.');
      return;
    }
    if (phone.replace(/\D/g, '').length < 10) {
      notice('입력 확인', '연락처를 정확히 입력해주세요.');
      return;
    }
    if (!agree) {
      notice('동의 필요', '개인정보 수집 및 이용에 동의해주세요.');
      return;
    }
    onSubmit({ name, phone, product });
    setName(''); setPhone(''); setProduct(''); setAgree(false);
  };

  return (
    <section id="apply" className="section section--subtle">
      <div className="container">
        <div className="form-card">
          <div className="form-brand">
            <img className="form-brand__logo" src={LOGO_SRC} alt="모원렌탈" width="200" height="64"/>
            <div className="form-brand__tag">전문 상담사가 친절하게 안내해드립니다</div>
          </div>
          <h2 className="form-title">지금 <span style={{color:'var(--coway)'}}>무료 상담</span> 신청하기</h2>

          <form onSubmit={submit}>
            <div className="field">
              <label className="field__label">성명<span className="req">*</span></label>
              <input type="text" className="input" placeholder="이름을 입력해주세요"
                value={name} onChange={(e)=>setName(e.target.value)}/>
            </div>
            <div className="field">
              <label className="field__label">연락처<span className="req">*</span></label>
              <input type="tel" className="input" placeholder="010-0000-0000"
                value={phone} onChange={(e)=>setPhone(formatPhone(e.target.value))}/>
            </div>
            <div className="field">
              <label className="field__label">희망제품</label>
              <select className="select" value={product} onChange={(e)=>setProduct(e.target.value)}>
                <option value="">선택 안함 (선택사항)</option>
                {products.map(p => <option key={p} value={p}>{p}</option>)}
              </select>
            </div>

            <div className="agree" onClick={()=>setAgree(!agree)}>
              <div className={`agree__checkbox ${agree?'is-checked':''}`}></div>
              <div className="agree__text">
                <b>개인정보수집 및 이용 동의 (필수)</b><br/>
                상담 목적으로만 사용되며, 상담 완료 후 개인정보는 안전하게 파기됩니다.
              </div>
            </div>

            <button type="submit" className="submit-btn">
              <I.Phone width="20" height="20"/>무료 상담 신청하기
            </button>
          </form>

          <div className="license-badge">
            <div className="license-badge__seal">
              <I.Seal/>공식 파트너 · 모원렌탈 정식 안내
            </div>
            <div className="license-badge__sub">사업자·통신판매 등 상세 정보는 상담 시 안내드립니다.</div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Benefits ---------- */
function Benefits() {
  const items = [
    { n:'01', icon:<I.Gift/>, label:'최대지원 + 사은품', title:<>당일 <span className="accent">설치지원</span></>, gold:true },
    { n:'02', icon:<I.Calendar/>, label:'전 모델 렌탈료', title:<>3개월 <span className="gold-pill">면제</span></> },
    { n:'03', icon:<I.Percent/>, label:'결합 할인 · 동시구매', title:<>동시구매<br/>최대 10% 할인</> },
    { n:'04', icon:<I.Shield/>, label:'타사 보상지원', title:<>위약금<br/>100% 보상</> },
  ];
  return (
    <section className="section">
      <div className="container">
        <div className="section-kicker is-gold">SPECIAL BENEFITS</div>
        <h2 className="section-title">모원렌탈만의 <span className="mark-gold">특별한</span><br/>추가 혜택!</h2>
        <p className="section-sub">다른 곳에서는 받을 수 없는 모원렌탈 전용 혜택을 모두 모았습니다</p>
        <div className="benefits-grid">
          {items.map(it => (
            <div key={it.n} className="benefit">
              <div className="benefit__num">{it.n}</div>
              <div className={`benefit__icon ${it.gold?'is-gold':''}`}>{it.icon}</div>
              <div className="benefit__label">{it.label}</div>
              <div className="benefit__title">{it.title}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Products ---------- */
function Products() {
  const list = window.PRODUCT_CATALOG && window.PRODUCT_CATALOG.length
    ? window.PRODUCT_CATALOG
    : [
        { name:'스위치 무선 정수기', v:'purifier', price:'15,900', card:'월 0원~', tags:['정수','무선'], hot:true },
        { name:'나노직수 미니 정수기', v:'purifier', price:'15,900', card:'월 0원~', tags:['정수','나노직수'] },
        { name:'아이콘2 정수기', v:'purifier', price:'14,200', card:'월 3,400원~', tags:['냉수','온수','정수'] },
        { name:'아이콘3 정수기', v:'purifier', price:'14,450', card:'월 3,900원~', tags:['냉수','온수','정수'] },
        { name:'아이콘 프로 정수기', v:'purifier', price:'14,950', card:'월 4,900원~', tags:['냉수','온수','정수'], hot:true },
        { name:'미니 얼음정수기', v:'ice', price:'21,450', card:'월 17,900원~', tags:['얼음','냉수','온수'] },
        { name:'스탠다드 얼음정수기', v:'ice', price:'22,950', card:'월 20,900원~', tags:['얼음','냉수','온수'] },
        { name:'얼음정수기 RO(지하수)', v:'ice', price:'20,200', card:'월 15,400원~', tags:['얼음','RO','지하수'] },
        { name:'아이콘 스탠드 정수기', v:'purifier', price:'12,950', card:'월 900원~', tags:['냉수','온수','정수'] },
        { name:'스스로케어 비데', v:'bidet', price:'18,400', card:'월 7,900원~', tags:['99% 항균','살균'] },
        { name:'더블케어 비데2', v:'bidet', price:'24,400', card:'월 12,900원~', tags:['터치리모컨','IPX방수'] },
        { name:'노블 제습공기청정기', v:'air', price:'18,950', card:'월 12,900원~', tags:['21L제습','4단필터'] },
      ];
  return (
    <section className="section section--subtle" id="products">
      <div className="container">
        <div className="section-kicker">BEST RENTAL</div>
        <h2 className="section-title"><span className="mark">인기 렌탈</span> 제품</h2>
        <p className="section-sub">고객이 가장 많이 선택한 모원렌탈 베스트 라인업</p>
        <div className="product-grid">
          {list.map((p, i) => (
            <div key={p.slug || i} className="product">
              {p.detailUrl ? (
                <a
                  className="product__link"
                  href={p.detailUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <div className="product__image">
                    <ProductThumb variant={p.v} image={p.image} name={p.name}/>
                    {p.hot && <div className="product__ribbon">HOT</div>}
                    <div className="product__rating"><I.Star/>4.8</div>
                  </div>
                  <h3 className="product__name">{p.name}</h3>
                </a>
              ) : (
                <>
                  <div className="product__image">
                    <ProductThumb variant={p.v} image={p.image} name={p.name}/>
                    {p.hot && <div className="product__ribbon">HOT</div>}
                    <div className="product__rating"><I.Star/>4.8</div>
                  </div>
                  <h3 className="product__name">{p.name}</h3>
                </>
              )}
              <div className="product__tags">
                {p.tags.map(t => <span key={t} className="product__tag">{t}</span>)}
              </div>
              <div className="product__price">
                <div className="product__price-label">월 렌탈료</div>
                <div className="product__price-main">
                  {p.price}<span className="won">원</span><span className="tilde">~</span>
                </div>
                <div className="product__price-sub">제휴카드 사용시 {p.card}</div>
                {p.detailUrl && (
                  <a
                    className="product__detail"
                    href={p.detailUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    자세히보기
                  </a>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Gifts ---------- */
function Gifts() {
  const [currentPage, setCurrentPage] = useState(0);
  const [giftsPerPage, setGiftsPerPage] = useState(() => (window.innerWidth <= 767 ? 9 : 4));
  const railRef = useRef(null);
  const gifts = [
    { name: '[멘토] 무릎 케어 알파 다리마사지기 MT-22A', fileName: '[멘토] 무릎 케어 알파 다리마사지기 MT-22A.png', price: '470,000', code: '437412', icon: <I.Package/> },
    { name: '[다룸] 제로컬렉션 무선청소기 자동 먼지비움 스마트 타워 스테이션 물걸레키트 추가', fileName: '[다룸] 제로컬렉션 무선청소기 자동 먼지비움 스마트 타워 스테이션 물걸레키트 추가.png', price: '349,000', code: '437439', icon: <I.Wind/> },
    { name: '[퓨어포스] 자동충전 스마트 로봇청소기 물걸레 겸용 NKF24_R11', fileName: '[퓨어포스] 자동충전 스마트 로봇청소기 물걸레 겸용 NKF24_R11.png', price: '189,000', code: '437121', icon: <I.Package/> },
    { name: '파세코 바디드라이어2 전신에어샤워 바디건조기 PBD-MT4120W', fileName: '파세코 바디드라이어2 전신에어샤워 바디건조기 PBD-MT4120W.png', price: '166,000', code: '418106', icon: <I.Package/> },
    { name: '파세코 바디드라이어 PBD-MT9130W(커버포함)', fileName: '파세코 바디드라이어 PBD-MT9130W(커버포함).png', price: '159,000', code: '418105', icon: <I.Package/> },
    { name: '[휴플러스] 아치톡스 HPF-550', fileName: '[휴플러스] 아치톡스 HPF-550.png', price: '158,000', code: '435021', icon: <I.Package/> },
    { name: '파세코 캠핑 등유 난로 CAMP-10 SUNSET(가방포함)', fileName: '파세코 캠핑 등유 난로 CAMP-10 SUNSET(가방포함).png', price: '156,000', code: '', icon: <I.Package/> },
    { name: '홈리아 더스트봇 충전ver HA-X520V02W', fileName: '홈리아 더스트봇 충전ver HA-X520V02W.png', price: '155,000', code: '도매가', icon: <I.Package/> },
    { name: '[콕스타] 쉬니 UV 젖병살균기 KSBSZ', fileName: '[콕스타] 쉬니 UV 젖병살균기 KSBSZ.png', price: '147,000', code: '436351', icon: <I.Package/> },
    { name: '파세코 욕실용히터 PHH-KF15W', fileName: '파세코 욕실용히터 PHH-KF15W.png', price: '108,000', code: '418118', icon: <I.Package/> },
    { name: '[티나인랩] 티나인 BLDC 4in1 멀티 헤어스타일러&드라이기 티니롤 TLB-STR4000', fileName: '[티나인랩] 티나인 BLDC 4in1 멀티 헤어스타일러&드라이기 티니롤 TLB-STR4000.png', price: '100,000', code: '437791', icon: <I.Package/> },
    { name: '휴빅 더포스 V2000 무선 청소기 HB-V2000W', fileName: '휴빅 더포스 V2000 무선 청소기 HB-V2000W.png', price: '88,000', code: '438174', icon: <I.Package/> },
    { name: '[앱코 오엘라] 바디케어 EMS 두피 마사지기 SM02-RS17', fileName: '[앱코 오엘라] 바디케어 EMS 두피 마사지기 SM02-RS17.png', price: '79,000', code: '438417', icon: <I.Package/> },
    { name: '비브르 가열식 가습기 3.5L 물멍 대용량 RU-G90U', fileName: '비브르 가열식 가습기 3.5L 물멍 대용량 RU-G90U.png', price: '76,000', code: '422845', icon: <I.Package/> },
    { name: '[자일렉] 침구 청소기 ZL-264B', fileName: '[자일렉] 침구 청소기 ZL-264B.png', price: '70,200', code: '436312', icon: <I.Package/> },
    { name: '[가이타이너] 자우버 2in1 스팀다리미 GTLIR2IN1', fileName: '[가이타이너] 자우버 2in1 스팀다리미 GTLIR2IN1.png', price: '68,500', code: '419561', icon: <I.Package/> },
    { name: '[리히텐] 2026년 신상품 LED 무드등 날개없는 선풍기 SN-TF200R (리포컨 포함/1년 무상AS)', fileName: '[리히텐] 2026년 신상품 LED 무드등 날개없는 선풍기 SN-TF200R (리포컨 포함1년 무상AS).png', price: '66,000', code: '438333', icon: <I.Package/> },
    { name: '[BRITZ] 브리츠 ACN1000XL4 노이즈캔슬링 블루투스 유무선 헤드폰 헤드셋', fileName: '[BRITZ] 브리츠 ACN1000XL4 노이즈캔슬링 블루투스 유무선 헤드폰 헤드셋.png', price: '64,000', code: '418899', icon: <I.Package/> },
    { name: '[레이코] 캣츠미 무선 침구청소기 SH-BC500', fileName: '[레이코] 캣츠미 무선 침구청소기 SH-BC500.png', price: '58,800', code: '437377', icon: <I.Package/> },
    { name: '비스카 날개 없는 선풍기(전자식) VK-D101R', fileName: '비스카 날개 없는 선풍기(전자식) VK-D101R.png', price: '55,900', code: '416859', icon: <I.Package/> },
    { name: '[앱코 오엘라] 바디케어 공기압 온열 다리 마사지기 LM01-FE7306', fileName: '[앱코 오엘라] 바디케어 공기압 온열 다리 마사지기 LM01-FE7306.png', price: '54,000', code: '438415', icon: <I.Package/> },
    { name: '[휴스톰] 헤어제트 BLDC 항공모터 헤어 드라이기 BLDC-7HS(거치대 포함)', fileName: '[휴스톰] 헤어제트 BLDC 항공모터 헤어 드라이기 BLDC-7HS(거치대 포함).png', price: '50,400', code: '421973', icon: <I.Package/> },
    { name: '[모노테일] 오드리 저소음 자동센서 스마트 휴지통 20L MT-AT50', fileName: '[모노테일] 오드리 저소음 자동센서 스마트 휴지통 20L MT-AT50.png', price: '49,900', code: '435363', icon: <I.Package/> },
    { name: '[데코아르] 멜로우 욕실온풍기 TKC-10047 (보관가방 증정)', fileName: '[데코아르] 멜로우 욕실온풍기 TKC-10047 (보관가방 증정).png', price: '48,000', code: '', icon: <I.Package/> },
    { name: '루베크 PTC 온풍기 RU-PH5910W', fileName: '루베크 PTC 온풍기 RU-PH5910W.png', price: '48,000', code: '416680', icon: <I.Package/> },
    { name: '[신일] 프리미엄 1구 인덕션 전기레인지 SHL-M2000BK / SHL-M2000WT', fileName: '[신일] 프리미엄 1구 인덕션 전기레인지 SHL-M2000BK  SHL-M2000WT.png', price: '47,200', code: '436102', icon: <I.Package/> },
    { name: '한경희 온풍 전기 컨벡션히터 HA-CV300', fileName: '한경희 온풍 전기 컨벡션히터 HA-CV300.png', price: '46,500', code: '415425', icon: <I.Package/> },
    { name: '셰퍼 릴리브 무선 목어깨마사지기 JSK-N3049', fileName: '셰퍼 릴리브 무선 목어깨마사지기 JSK-N3049.png', price: '29,500', code: '416505', icon: <I.Package/> },
    { name: '[루티네] 펄스 밴드 손목 저주파 마사지기 RT-2530', fileName: '[루티네] 펄스 밴드 손목 저주파 마사지기 RT-2530.png', price: '17,500', code: '436028', icon: <I.Package/> },
    { name: '[2026년형] 와커 거꾸로 올라가는 USB 물방울 가습기 화이트', fileName: '[2026년형] 와커 거꾸로 올라가는 USB 물방울 가습기 화이트.png', price: '14,000', code: '420095', icon: <I.Package/> },
  ];
  const chunk = (arr, size) => {
    const pages = [];
    for (let i = 0; i < arr.length; i += size) pages.push(arr.slice(i, i + size));
    return pages;
  };
  const giftPages = chunk(gifts, giftsPerPage);
  const pageCount = Math.max(1, giftPages.length);

  useEffect(() => {
    const onResize = () => {
      setGiftsPerPage(window.innerWidth <= 767 ? 9 : 4);
    };
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  useEffect(() => {
    setCurrentPage(0);
    if (railRef.current) railRef.current.scrollTo({ left: 0, behavior: 'auto' });
  }, [giftsPerPage]);

  const scrollToPage = (nextPage) => {
    const rail = railRef.current;
    if (!rail || pageCount <= 1) return;
    const clamped = Math.max(0, Math.min(nextPage, pageCount - 1));
    rail.scrollTo({ left: rail.clientWidth * clamped, behavior: 'smooth' });
    setCurrentPage(clamped);
  };

  const onRailScroll = () => {
    const rail = railRef.current;
    if (!rail || !rail.clientWidth || pageCount <= 1) return;
    const page = Math.round(rail.scrollLeft / rail.clientWidth);
    setCurrentPage(Math.max(0, Math.min(page, pageCount - 1)));
  };

  return (
    <section className="section section--subtle">
      <div className="container">
        <div className="section-kicker is-gold">GIFT COLLECTION</div>
        <h2 className="section-title">모원 <span className="mark-gold">사은품</span> 컬렉션</h2>
        <div className="product-grid gift-product-grid" ref={railRef} onScroll={onRailScroll}>
          {giftPages.map((page, pageIdx) => (
            <div key={pageIdx} className="gift-page">
              {page.map((g) => (
                <article key={g.name} className="product gift-product">
                  <div className="product__image">
                    <GiftNewThumb fileName={g.fileName} label={g.name} icon={g.icon}/>
                  </div>
                  <h3 className="product__name">{g.name}</h3>
                </article>
              ))}
            </div>
          ))}
        </div>
        <div className={`cards-controls ${pageCount <= 1 ? 'is-hidden' : ''}`} aria-label="사은품 슬라이드 컨트롤">
          <button
            type="button"
            className="cards-navbtn"
            onClick={() => scrollToPage(currentPage - 1)}
            disabled={currentPage <= 0}
            aria-label="이전 사은품"
          >
            ‹
          </button>
          <button
            type="button"
            className="cards-navbtn"
            onClick={() => scrollToPage(currentPage + 1)}
            disabled={currentPage >= pageCount - 1}
            aria-label="다음 사은품"
          >
            ›
          </button>
        </div>
        <div className={`cards-page-indicator ${pageCount <= 1 ? 'is-hidden' : ''}`} aria-live="polite">
          {currentPage + 1}/{pageCount}
        </div>
      </div>
    </section>
  );
}

/* ---------- Trust ---------- */
function Trust() {
  const ref = useRef(null);
  const inView = useInView(ref);
  const stats = [
    { num:1200, suf:'만대', label:'누적 설치' },
    { num:97.2, suf:'%',   label:'고객 만족도', decimal:true },
    { num:6000, suf:'명',  label:'서비스망' },
    { num:1,    suf:'위',  label:'품질 만족지수' },
    { num:1,    suf:'위',  label:'업계 점유율' },
    { num:20,   suf:'년+', label:'브랜드 역사' },
  ];
  return (
    <section className="trust-hero" ref={ref} data-screen-label="07 Trust">
      <div className="container trust-hero__inner">
        <div className="trust-hero__kicker">WHY MOWON</div>
        <h2 className="trust-hero__title">
          왜 렌탈은<br/>
          <span className="gold">모원렌탈</span>과 함께할까요?
        </h2>
        <p className="trust-hero__sub">매일 마시는 물이니까, 더 믿을 수 있는 선택이 필요합니다.</p>

        <div className="trust-grid">
          {stats.map((s, i) => {
            const val = useCountUp(Math.floor(s.num), inView, 1800);
            const display = s.decimal ? (inView ? s.num.toFixed(1) : '0.0') : val.toLocaleString();
            return (
              <div key={i} className="trust-stat">
                <div className="trust-stat__num">{display}{s.suf}</div>
                <div className="trust-stat__label">{s.label}</div>
              </div>
            );
          })}
        </div>

        <div className="trust-footer">
          <div className="trust-footer__badge">믿고 쓰는 1등 브랜드</div>
          <div className="trust-footer__msg">당신의 첫 렌탈은<br/><span style={{color:'var(--gold-400)'}}>모원렌탈</span>과 함께하세요.</div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Compare Table ---------- */
function Compare() {
  const rows = [
    { label:'편리함',   good:'간편한 이용',     bad:'반복 구매' },
    { label:'운반',     good:'설치만 하면 끝',  bad:'무거운 박스 운반' },
    { label:'주문',     good:'자동 공급',       bad:'지속적 재주문' },
    { label:'경제성',   good:'저렴한 비용',     bad:'장기 고비용' },
    { label:'위생',     good:'정기 관리 서비스', bad:'보관 공간 필요' },
    { label:'환경',     good:'친환경',          bad:'폐기물 증가' },
  ];
  return (
    <section className="section">
      <div className="container">
        <div className="section-kicker">SMART CHOICE</div>
        <h2 className="section-title">매달 <span className="mark">생수</span> 사느라<br/>번거로우셨죠?</h2>
        <p className="section-sub">정수기와 생수, 직접 비교해보면 답이 나옵니다.<br/>더 위생적이고, 더 편리하고, 더 저렴해요.</p>

        <div className="compare">
          <div className="compare__row compare__head">
            <div className="compare__cell compare__cell--label">항목</div>
            <div className="compare__cell compare__cell--good">정수기</div>
            <div className="compare__cell">생수</div>
          </div>
          {rows.map(r => (
            <div key={r.label} className="compare__row">
              <div className="compare__cell compare__cell--label">{r.label}</div>
              <div className="compare__cell compare__cell--good">
                <span className="compare__mark good">○</span>
                <span>{r.good}</span>
              </div>
              <div className="compare__cell compare__cell--bad">
                <span className="compare__mark bad">✕</span>
                <span>{r.bad}</span>
              </div>
            </div>
          ))}
        </div>

        <div className="compare-outro">
          정수기로 바꾸는 순간부터<br/>매일이 더 가벼워집니다.
        </div>
      </div>
    </section>
  );
}

/* ---------- Cards (제휴카드 안내) ---------- */
function Cards() {
  const [activeCategory, setActiveCategory] = useState('ALL');
  const [cardsPerPage, setCardsPerPage] = useState(() => (window.innerWidth <= 767 ? 2 : 3));
  const [currentPage, setCurrentPage] = useState(0);
  const railRef = useRef(null);

  const categories = ['ALL', '코웨이', 'SK매직', 'LG전자', '청호나이스'];

  const cards = [
    { name:'코웨이 신한카드', image:'images/제휴카드/코웨이/코웨이신한카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>13,000원</b> 할인','전월실적 70만원 이상 시 월 <b>17,000원</b> 할인','전월실적 150만원 이상 시 월 <b>30,000원</b> 할인'], promo:['4월 신규발급 프로모션','30만원 구간 <b>10,000원</b> 추가할인','70만원 구간 <b>6,000원</b> 추가할인'], fee:'국내전용 27,000원 / 해외겸용(MASTER) 30,000원', phone:'02-1833-6013' },
    { name:'코웨이 NH카드', image:'images/제휴카드/코웨이/코웨이NH카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>10,000원</b> 할인','전월실적 100만원 이상 시 월 <b>15,000원</b> 할인','전월실적 200만원 이상 시 월 <b>30,000원</b> 할인'], promo:['4월 신규발급 프로모션','전 구간 <b>10,000원</b> 추가할인'], fee:'연회비 국내전용 10,000원 / 국내외겸용(MASTER) 12,000원', phone:'1644-2866' },
    { name:'코웨이 하나카드', image:'images/제휴카드/코웨이/코웨이하나카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>13,000원</b> 할인','전월실적 80만원 이상 시 월 <b>18,000원</b> 할인','전월실적 150만원 이상 시 월 <b>25,000원</b> 할인'], fee:'국내전용 / 국내외겸용(Master card) 25,000원', phone:'1588-1771' },
    { name:'코웨이 X LOCA 롯데카드', image:'images/제휴카드/코웨이/코웨이XLOCA롯데카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>13,000원</b> 할인','전월실적 70만원 이상 시 월 <b>16,000원</b> 할인','전월실적 150만원 이상 시 월 <b>25,000원</b> 할인'], promo:['4월 신규발급자 대상 프로모션 (60개월간 적용)','30만원 구간 <b>3,000원</b> 추가할인','70만원 구간 <b>2,000원</b> 추가할인'], fee:'국내전용, 해외겸용(MASTER) 20,000원', phone:'1577-5208' },
    { name:'코웨이 ICON 우리카드', image:'images/제휴카드/코웨이/코웨이ICON우리카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>13,000원</b> 할인','전월실적 80만원 이상 시 월 <b>17,000원</b> 할인','전월실적 150만원 이상 시 월 <b>23,000원</b> 할인'], promo:['4월 신규발급 프로모션 (60개월간 적용)','30/80/150 구간 <b>9,000원 / 7,000원 / 7,000원</b> 추가할인'], fee:'국내전용 / 해외겸용(MasterCard) 15,000원', phone:'1800-3182' },
    { name:'코웨이 IBK카드', image:'images/제휴카드/코웨이/코웨이IBK카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>13,000원</b> 할인','전월실적 70만원 이상 시 월 <b>17,000원</b> 할인','전월실적 120만원 이상 시 월 <b>23,000원</b> 할인'], fee:'연회비 국내전용 12,000원 / 국내외겸용 UnionPay 15,000원 / Master 15,000원', phone:'1566-0088' },
    { name:'코웨이 현대카드', image:'images/제휴카드/코웨이/코웨이현대카드/1.png', benefits:['전월실적 50만원 이상 시 월 <b>15,000원</b> 할인','전월실적 100만원 이상 시 월 <b>20,000원</b> 할인'], promo:['4월 신규발급자 대상 프로모션 (36개월간 적용)','50만원/100만원 구간 <b>10,000원</b> 추가할인'], fee:'연회비 국내전용 30,000원 / 국내외겸용(VISA/Master card) 30,000원', phone:'02-2655-5003' },
    { name:'코웨이 삼성카드', image:'images/제휴카드/코웨이/코웨이삼성카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>7,000원</b> 할인','전월실적 70만원 이상 시 월 <b>10,000원</b> 할인','전월실적 120만원 이상 시 월 <b>13,000원</b> 할인'], promo:['4월 신규발급자 대상 프로모션 (60개월 적용)','전 구간 <b>11,000원</b> 추가할인'], fee:'국내전용 15,000원 / 국내외겸용(VISA) 15,000원', phone:'1588-7540' },
    { name:'코웨이 KB국민카드2', image:'images/제휴카드/코웨이/코웨이KB국민카드2/1.png', benefits:['전월실적 40만원 이상 시 월 <b>15,000원</b> 할인','전월실적 80만원 이상 시 월 <b>20,000원</b> 할인'], promo:['4월 신규발급자 대상 프로모션 (60개월간 적용)','전 구간 <b>10,000원</b> 추가할인'], fee:'연회비 국내외겸용(MASTER) 30,000원', phone:'1644-8388' },
    { name:'청호나이스 신한카드', image:'images/제휴카드/청호나이스/청호나이스신한카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>12,000원</b> 할인','전월실적 70만원 이상 시 월 <b>16,000원</b> 할인','전월실적 150만원 이상 시 월 <b>30,000원</b> 할인'], promo:['4월 신규발급 프로모션','30만원 구간 <b>3,000원</b> 추가할인'], fee:'국내전용 15,000원 / 해외겸용 18,000원', phone:'1833-2061' },
    { name:'청호나이스 롯데카드', image:'images/제휴카드/청호나이스/청호나이스롯데카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>10,000원</b> 할인','전월실적 70만원 이상 시 월 <b>15,000원</b> 할인','전월실적 150만원 이상 시 월 <b>25,000원</b> 할인'], promo:['4월 신규발급 프로모션','30만원 구간 <b>8,000원</b> 추가할인','70만원 구간 <b>5,000원</b> 추가할인'], fee:'연회비 국내전용 12,000원 / 국내외겸용 15,000원', phone:'1577-5633' },
    { name:'청호나이스 KB국민카드', image:'images/제휴카드/청호나이스/청호나이스KB국민카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>12,000원</b> 할인','전월실적 70만원 이상 시 월 <b>17,000원</b> 할인'], promo:['4월 신규발급 프로모션','30만원 구간 <b>8,000원</b> 추가할인','70만원 구간 <b>3,000원</b> 추가할인'], fee:'국내외겸용 15,500원', phone:'1644-8466' },
    { name:'청호나이스 삼성카드', image:'images/제휴카드/청호나이스/청호나이스삼성카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>7,000원</b> 할인','전월실적 70만원 이상 시 월 <b>10,000원</b> 할인','전월실적 120만원 이상 시 월 <b>13,000원</b> 할인'], promo:['4월 신규발급 프로모션','전 구간 <b>11,000원</b> 추가할인'], fee:'국내전용 15,000원 / 해외겸용(MASTER) 15,000원', phone:'1588-6076' },
    { name:'SK매직 롯데카드', image:'images/제휴카드/SK매직/SK매직롯데카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>13,000원</b> 할인','전월실적 70만원 이상 시 월 <b>16,000원</b> 할인','전월실적 120만원 이상 시 월 <b>25,000원</b> 할인'], promo:['2026.04 프로모션','30만원 구간 <b>2,000원</b> 추가할인 (60개월)','70만원 구간 <b>1,000원</b> 추가할인 (60개월)'], fee:'국내해외겸용 20,000원', phone:'1577-5320' },
    { name:'SK매직 KB국민카드', image:'images/제휴카드/SK매직/SK매직KB국민카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>11,000원</b> 할인','전월실적 70만원 이상 시 월 <b>15,000원</b> 할인','전월실적 100만원 이상 시 월 <b>20,000원</b> 할인'], promo:['2026.04 프로모션 추가할인','30만원 구간 <b>9,000원</b> 추가할인','70만원 구간 <b>5,000원</b> 추가할인'], fee:'국내전용 12,000원 / 국내외겸용(MasterCard) 15,000원', phone:'1644-8466' },
    { name:'SK매직 삼성카드', image:'images/제휴카드/SK매직/SK매직삼성카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>7,000원</b> 할인','전월실적 70만원 이상 시 월 <b>10,000원</b> 할인','전월실적 120만원 이상 시 월 <b>13,000원</b> 할인'], promo:['2026.04 프로모션','전 구간 <b>10,000원</b> 추가할인'], fee:'연회비 국내전용/해외겸용(Master card) 15,000원', phone:'1599-6758' },
    { name:'SK매직 KJ카드', image:'images/제휴카드/SK매직/SK매직KJ카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>10,000원</b> 할인','전월실적 70만원 이상 시 월 <b>16,000원</b> 할인','전월실적 120만원 이상 시 월 <b>23,000원</b> 할인'], fee:'연회비 국내전용 14,000원 / 국내외겸용(Master card) 15,000원', phone:'1833-3684' },
    { name:'쿠쿠 X 롯데카드', image:'images/제휴카드/쿠쿠/쿠쿠X롯데카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>13,000원</b> 할인','전월실적 70만원 이상 시 월 <b>16,000원</b> 할인','전월실적 150만원 이상 시 월 <b>25,000원</b> 할인'], promo:['2026.04 신규발급 프로모션','30만원 구간 <b>2,000원</b> 추가할인','70만원 구간 <b>1,000원</b> 추가할인'], fee:'국내전용, 해외겸용(MASTER) 20,000원', phone:'1577-7182' },
    { name:'쿠쿠 우리카드', image:'images/제휴카드/쿠쿠/쿠쿠우리카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>10,000원</b> 할인','전월실적 70만원 이상 시 월 <b>15,000원</b> 할인','전월실적 100만원 이상 시 월 <b>20,000원</b> 할인'], promo:['2026.04 신규발급 프로모션','30/70/120 구간 <b>8,000원 / 5,000원 / 3,000원</b> 추가할인'], fee:'연회비 국내 15,000원 / MasterCard 15,000원', phone:'1800-4138' },
    { name:'쿠쿠 삼성카드', image:'images/제휴카드/쿠쿠/쿠쿠삼성카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>7,000원</b> 할인','전월실적 70만원 이상 시 월 <b>10,000원</b> 할인','전월실적 120만원 이상 시 월 <b>13,000원</b> 할인'], promo:['2026.04 신규발급 프로모션','전 구간 <b>10,000원</b> 추가할인'], fee:'국내전용, 해외겸용(VISA) 15,000원', phone:'1588-9260' },
    { name:'쿠쿠 신한카드', image:'images/제휴카드/쿠쿠/쿠쿠신한카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>13,000원</b> 할인','전월실적 70만원 이상 시 월 <b>17,000원</b> 할인','전월실적 150만원 이상 시 월 <b>30,000원</b> 할인'], promo:['2026.04 신규발급 프로모션','30/70만원 구간 <b>2,000원</b> 추가할인'], fee:'국내전용 27,000원 / 해외겸용(VISA) 30,000원', phone:'1833-4303' },
    { name:'[우리] LG전자 우리카드 (Platinum)', image:'images/제휴카드/LG전자/LG전자우리카드(플래티넘)/1.png', benefits:['전월실적 100만원 이상 시 월 <b>29,000원</b> 할인','전월실적 150만원 이상 시 월 <b>34,000원</b> 할인','전월실적 200만원 이상 시 월 <b>40,000원</b> 할인'], promo:['4월 신규발급 프로모션','100/150/200만원 구간 <b>6,000원 / 5,000원 / 2,000원</b> 추가할인'], fee:'국내전용 / 해외겸용(VISA) 25,000원', phone:'1800-4137 / 온라인신청' },
    { name:'[우리] LG전자 우리카드', image:'images/제휴카드/LG전자/LG전자우리카드/1.png', benefits:['전월실적 30만원 이상 시 월 <b>10,000원</b> 할인','전월실적 70만원 이상 시 월 <b>15,000원</b> 할인','전월실적 120만원 이상 시 월 <b>20,000원</b> 할인'], promo:['4월 신규발급 추가할인 프로모션','30/70만원 구간 <b>7,000원</b> 추가할인','120만원 구간 <b>4,000원</b> 추가할인'], fee:'국내전용 15,000원 / 해외겸용(MasterCard) 15,000원', phone:'1800-4137 / 온라인신청' },
    { name:'[롯데] LG전자 롯데카드 구독엔로카', image:'images/제휴카드/LG전자/LG전자롯데카드구독엔로카/1.png', benefits:['전월실적 40만원 이상 시 월 <b>13,000원</b> 할인','전월실적 80만원 이상 시 월 <b>18,000원</b> 할인','전월실적 160만원 이상 시 월 <b>26,000원</b> 할인'], promo:['4월 신규발급 추가할인 프로모션','30만원 구간 <b>6,000원</b> 추가할인','70만원 구간 <b>4,000원</b> 추가할인'], fee:'국내전용, 해외겸용(MASTER/AMEX) 20,000원', phone:'1577-9469' },
    { name:'[신한] LG전자 신한카드 더구독케어', image:'images/제휴카드/LG전자/LG전자신한카드더구독케어/1.png', benefits:['전월실적 30만원 이상 시 월 <b>13,000원</b> 할인','전월실적 70만원 이상 시 월 <b>16,000원</b> 할인','전월실적 130만원 이상 시 월 <b>20,000원</b> 할인'], promo:['4월 신규발급 추가할인 프로모션','30만원 구간 <b>4,000원</b> 추가할인','70만원 구간 <b>1,000원</b> 추가할인'], fee:'연회비 국내전용 22,000원 / 국내외겸용(Mastercard) 25,000원', phone:'온라인신청', link:'https://cardapply.shinhancard.com/apply/CardInfoSelect?EntryLoc=4440&empSeq=502&targetID=&dat' },
  ].map((card) => {
    const match = card.image.match(/^images\/제휴카드\/([^/]+)\//);
    return { ...card, brand: match ? match[1] : 'ALL' };
  });

  const filteredCards = activeCategory === 'ALL'
    ? cards
    : cards.filter((card) => card.brand === activeCategory);
  const stripHtml = (text) => text.replace(/<[^>]+>/g, '');
  const parseTier = (line) => {
    const plain = stripHtml(line);
    const cond = plain.match(/전월실적\s*([0-9/]+만원)\s*이상/);
    const amount = plain.match(/([0-9,]+원)/);
    if (!cond || !amount) return null;
    return { condition: cond[1] + ' 이상', amount: amount[1], raw: amount[1].replace(/[^\d]/g, '') };
  };
  const compactCards = filteredCards.map((card) => {
    const tiers = (card.benefits || []).map(parseTier).filter(Boolean);
    const max = tiers.reduce((acc, t) => Math.max(acc, Number(t.raw || 0)), 0);
    return {
      ...card,
      tiers,
      maxText: max > 0 ? `${max.toLocaleString('ko-KR')}원` : '-',
    };
  });
  const categoryLabel = activeCategory === 'ALL' ? '전체 제휴카드 안내' : `${activeCategory} 제휴카드 안내`;
  const chunkCards = (list, size) => {
    const chunks = [];
    for (let i = 0; i < list.length; i += size) {
      chunks.push(list.slice(i, i + size));
    }
    return chunks;
  };
  const pagedCards = chunkCards(compactCards, cardsPerPage).map((group) => {
    if (group.length < cardsPerPage) {
      return [...group, ...Array.from({ length: cardsPerPage - group.length }, () => ({ isPlaceholder: true, name: '__placeholder__' }))];
    }
    return group;
  });
  const pageCount = Math.max(1, pagedCards.length);

  useEffect(() => {
    const onResize = () => {
      setCardsPerPage(window.innerWidth <= 767 ? 2 : 3);
    };
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  useEffect(() => {
    setCurrentPage(0);
    if (railRef.current) railRef.current.scrollTo({ left: 0, behavior: 'auto' });
  }, [activeCategory, cardsPerPage]);

  const scrollToPage = (nextPage) => {
    const rail = railRef.current;
    if (!rail || pageCount <= 1) return;
    const clamped = Math.max(0, Math.min(nextPage, pageCount - 1));
    rail.scrollTo({
      left: rail.clientWidth * clamped,
      behavior: 'smooth',
    });
    setCurrentPage(clamped);
  };

  const onRailScroll = () => {
    const rail = railRef.current;
    if (!rail || !rail.clientWidth || pageCount <= 1) return;
    const page = Math.round(rail.scrollLeft / rail.clientWidth);
    setCurrentPage(Math.max(0, Math.min(page, pageCount - 1)));
  };

  return (
    <section className="section section--subtle">
      <div className="container">
        <div className="section-kicker">PARTNER CARDS</div>
        <h2 className="section-title">스마트한 소비,<br/><span className="mark">실속있는</span> 혜택!</h2>
        <p className="section-sub">제휴카드를 활용하면 매달 렌탈료를 더 크게 절약할 수 있어요.</p>

        <div className="cards-cats" role="tablist" aria-label="제휴카드 카테고리">
          {categories.map((category) => (
            <button
              key={category}
              type="button"
              className={`cards-cat ${activeCategory === category ? 'is-active' : ''}`}
              onClick={() => setActiveCategory(category)}
            >
              {category}
            </button>
          ))}
        </div>

        <h3 className="cards-headline">{categoryLabel}</h3>

        <div className="cards-rail" ref={railRef} onScroll={onRailScroll}>
          {pagedCards.map((page, pageIdx) => (
            <div key={pageIdx} className="cards-page">
              {page.map((c, i) => (
                <article key={i} className={`pcard ${c.isPlaceholder ? 'is-placeholder' : ''}`}>
                  {c.isPlaceholder ? null : (
                    <>
                      <div className="pcard__media">
                        <img className="pcard__image" src={c.image} alt={c.name} loading="lazy" decoding="async"/>
                      </div>
                      <h4 className="pcard__name">{c.name}</h4>
                      <ul className="pcard__list">
                        {c.tiers.map((tier, idx) => (
                          <li key={idx}>
                            <span>{tier.condition}</span>
                            <b>{tier.amount}</b>
                          </li>
                        ))}
                      </ul>
                      <div className="pcard__max">최대 {c.maxText}</div>
                    </>
                  )}
                </article>
              ))}
            </div>
          ))}
        </div>
        <div className={`cards-controls ${pageCount <= 1 ? 'is-hidden' : ''}`} aria-label="카드 슬라이드 컨트롤">
          <button
            type="button"
            className="cards-navbtn"
            onClick={() => scrollToPage(currentPage - 1)}
            disabled={currentPage <= 0}
            aria-label="이전 카드"
          >
            ‹
          </button>
          <button
            type="button"
            className="cards-navbtn"
            onClick={() => scrollToPage(currentPage + 1)}
            disabled={currentPage >= pageCount - 1}
            aria-label="다음 카드"
          >
            ›
          </button>
        </div>
        <div className={`cards-dots ${pageCount <= 1 ? 'is-hidden' : ''}`} aria-hidden="true">
          {Array.from({ length: pageCount }).map((_, idx) => (
            <span key={idx} className={`cards-dot ${idx === currentPage ? 'is-active' : ''}`}></span>
          ))}
        </div>
        <p className="cards-footnote">※ 카드사 및 프로모션 정책은 변동될 수 있으며, 상세 조건은 카드사 안내 기준을 따릅니다.</p>
      </div>
    </section>
  );
}

/* ---------- Process ---------- */
function Process() {
  const steps = [
    { n:'01', title:'이벤트 신청',            desc:'쉽고 빠른 간편 상담 신청', icon:<I.User/> },
    { n:'02', title:'상담 및 신청서 작성',    desc:'상담 시 원하는 사은품 직접 선택', icon:<I.Gift/> },
    { n:'03', title:'설치 후 사은품 수령',    desc:'전국 어디든 당일 발송 시스템', icon:<I.Truck/> },
  ];
  return (
    <section className="section">
      <div className="container">
        <div className="section-kicker">EASY PROCESS</div>
        <h2 className="section-title">모원렌탈<br/><span className="mark">이벤트 절차</span></h2>
        <p className="section-sub">단 3단계로 끝나는 빠르고 간편한 상담</p>
        <div className="process">
          {steps.map(s => (
            <div key={s.n} className="step">
              <div className="step__num">{s.n}</div>
              <div className="step__body">
                <h4 className="step__title">{s.title}</h4>
                <div className="step__desc">{s.desc}</div>
              </div>
              <div className="step__icon">{s.icon}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Final CTA ---------- */
function FinalCTA({ onApply }) {
  return (
    <section className="final-cta" data-screen-label="12 Final CTA">
      <div className="container">
        <div className="final-cta__badge">🔥 전국 최저가 프로모션</div>
        <h2 className="final-cta__title">재고 소진 시,<br/><span className="gold">이벤트 종료!</span></h2>
        <p className="final-cta__sub">지금 신청하면 최대 혜택을 모두 받으실 수 있습니다.</p>
        <div className="final-cta__counter">
          <span className="final-cta__counter-lbl">선착순 100명 중 현재</span>
          <span className="final-cta__counter-num">77명</span>
          <span className="final-cta__counter-lbl">참여</span>
        </div>
        <button className="final-cta__btn" onClick={onApply}>
          <I.Phone width="22" height="22"/>무료 상담 신청하기
          <I.ArrowRight width="20" height="20"/>
        </button>
      </div>
    </section>
  );
}

/* ---------- Sticky CTA ---------- */
function StickyCTA({ onApply }) {
  return (
    <div className="sticky-cta">
      <div className="sticky-cta__inner">
        <a href={MAIN_PHONE_HREF} className="sticky-cta__call" aria-label={`대표번호 ${MAIN_PHONE} 전화 걸기`}>
          <I.Phone width="22" height="22"/>
        </a>
        <button className="sticky-cta__main" onClick={onApply}>
          <I.Gift width="18" height="18"/>
          무료 상담 신청 · 혜택 받기
        </button>
      </div>
    </div>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div><strong>모원렌탈</strong> · 공식 프로모션 안내</div>
        <div style={{marginTop:6}}>
          대표 <a href={MAIN_PHONE_HREF} className="footer__tel">{MAIN_PHONE}</a>
          {' '}· 평일 09:00–20:00 (주말/공휴일 상담가능)
        </div>
        <div style={{marginTop:6,opacity:0.6}}>© 2026 Mowon Rental. All rights reserved.</div>
      </div>
    </footer>
  );
}

/* ---------- Submitted Toast ---------- */
function Toast({ show, onDone }) {
  useEffect(() => {
    if (!show) return;
    const t = setTimeout(onDone, 2800);
    return () => clearTimeout(t);
  }, [show, onDone]);
  if (!show) return null;
  return (
    <div className="toast">
      <I.Check width="18" height="18"/>상담 신청이 접수되었습니다!
    </div>
  );
}

Object.assign(window, {
  Header, Hero, Status, InquiryForm, Benefits, Products, Gifts,
  Trust, Compare, Cards, Process, FinalCTA, StickyCTA, Footer, Toast, NoticeModal,
  LiveViewingBar,
});
