/* ============================================================
   invite-main.jsx — Thiệp cưới "Thanh lịch" · responsive (web + ĐT)
   Dùng lại khối chung từ invite-shared.jsx (WED, Photo, Sprig,
   useCountdown, MapButton, MusicPlayer, Reveal).
   ============================================================ */
const { useState, useEffect, useRef } = React;

const pad2 = (n) => String(n).padStart(2, '0');

/* ---------- Ảnh thật trong folder image/ — gán theo id slot ---------- */
const PHOTOS = {
  'hero-main': 'image/DSC_6096.jpg',
  'band-1':    'image/L1340434.jpg',
  'band-2':    'image/L1340194.jpg',
  'gal-0':     'image/L1340100.jpg',
  'gal-1':     'image/L1340194.jpg',
  'gal-2':     'image/L1340422.jpg',
  'gal-3':     'image/L1340434.jpg',
  'gal-4':     'image/DSC_6096.jpg',
  'gal-5':     'image/DSC_7069.jpg',
};

/* ---------- Ô ảnh (gán sẵn src, vẫn cho phép kéo-thả ghi đè) ---------- */
function ImgSlot({ id, placeholder, shape = 'rect', radius, fit = 'cover', style }) {
  const props = { id, placeholder, shape, fit, style };
  if (radius != null) props.radius = radius;
  if (PHOTOS[id]) props.src = PHOTOS[id];
  return React.createElement('image-slot', props);
}

/* ---------- Đếm ngược responsive ---------- */
function CountdownR() {
  const { d, h, m, s } = window.useCountdown(window.WED.dateISO);
  const items = [[d, 'Ngày'], [h, 'Giờ'], [m, 'Phút'], [s, 'Giây']];
  return (
    <div className="cd">
      {items.map(([v, lab]) => (
        <div className="cd-cell" key={lab}>
          <span className="cd-num">{pad2(v)}</span>
          <span className="m-eyebrow cd-lab">{lab}</span>
        </div>
      ))}
    </div>
  );
}

/* ---------- Dải ảnh full-bleed (điểm nhấn) + parallax chữ ---------- */
function Band({ id, lab, big, sub }) {
  const bandRef = useRef(null);
  const capRef = useRef(null);

  // Parallax: chữ trôi nhẹ ngược chiều cuộn — ghi thẳng DOM qua rAF,
  // biên độ giới hạn để không trôi quá đà.
  useEffect(() => {
    if (window.__reduceMotion) return;
    const band = bandRef.current, cap = capRef.current;
    if (!band || !cap) return;
    let raf = 0;
    const update = () => {
      raf = 0;
      const r = band.getBoundingClientRect();
      const vh = window.innerHeight;
      if (r.bottom < 0 || r.top > vh) return; // ngoài màn hình thì bỏ qua
      // tiến trình -1..1 khi band đi qua khung nhìn
      const prog = (r.top + r.height / 2 - vh / 2) / (vh / 2 + r.height / 2);
      const shift = Math.max(-40, Math.min(40, prog * -40)); // giới hạn ±40px
      cap.style.transform = 'translate3d(0,' + shift.toFixed(1) + 'px,0)';
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    update();
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); if (raf) cancelAnimationFrame(raf); };
  }, []);

  return (
    <div className="band" ref={bandRef}>
      <ImgSlot id={id} placeholder="Kéo ảnh cưới vào đây" />
      <div className="band__veil"></div>
      <div className="band__cap" ref={capRef}>
        {lab && <span className="lab">{lab}</span>}
        {big && <p className="big">{big}</p>}
        {sub && <span className="sub">{sub}</span>}
      </div>
    </div>
  );
}

/* ---------- Album slideshow (crossfade + auto-advance + dots) ---------- */
function GalleryR() {
  const ids = ['gal-0', 'gal-1', 'gal-2', 'gal-3', 'gal-4', 'gal-5'];
  const [idx, setIdx] = useState(0);
  const [paused, setPaused] = useState(false);
  const total = ids.length;

  useEffect(() => {
    if (paused) return;
    const t = setInterval(() => setIdx((i) => (i + 1) % total), 5000);
    return () => clearInterval(t);
  }, [paused, total]);

  const go = (n) => setIdx((n + total) % total);

  return (
    <div className="slideshow"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}>
      <div className="slideshow__stage">
        {ids.map((id, i) => (
          <div key={id} className={'slide' + (i === idx ? ' is-active' : '')}>
            <ImgSlot id={id} placeholder={'Ảnh ' + (i + 1)}
              style={{ display: 'block', width: '100%', height: '100%' }} />
          </div>
        ))}
        <button className="slide-nav slide-nav--prev" onClick={() => go(idx - 1)} aria-label="Ảnh trước">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
        </button>
        <button className="slide-nav slide-nav--next" onClick={() => go(idx + 1)} aria-label="Ảnh tiếp">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6"/></svg>
        </button>
        <div className="slide-counter">{pad2(idx + 1)} / {pad2(total)}</div>
      </div>
      <div className="slide-dots">
        {ids.map((_, i) => (
          <button key={i} className={'dot' + (i === idx ? ' is-active' : '')}
            onClick={() => go(i)} aria-label={'Đi tới ảnh ' + (i + 1)} />
        ))}
      </div>
    </div>
  );
}

/* ---------- Nhãn + gạch mảnh ---------- */
function LabelRule({ children }) {
  return (
    <div className="label-rule">
      <span className="m-eyebrow">{children}</span>
      <span className="hairline"></span>
    </div>
  );
}

/* ---------- Bìa thiệp ---------- */
function Cover({ open, onOpen }) {
  const W = window.WED;
  return (
    <div className={'cover' + (open ? ' is-open' : '')}>
      <window.Sprig size={56} color="var(--sage)" />
      <p className="m-eyebrow" style={{ margin: '22px 0 26px' }}>Save the date</p>
      <h1 className="m-names" style={{ fontSize: 'clamp(40px,11vw,76px)' }}>
        <span className="ln" style={{ fontSize: 'clamp(40px,11vw,76px)' }}>{W.groom}</span>
        <span className="m-amp">&amp;</span>
        <span className="ln" style={{ fontSize: 'clamp(40px,11vw,76px)' }}>{W.bride}</span>
      </h1>
      <p style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 'clamp(15px,3vw,20px)', color: 'var(--ink-soft)', margin: '20px 0 30px' }}>{W.dateLong}</p>
      <button className="m-btn m-btn--solid" onClick={onOpen}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16v16H4z"/><path d="M4 7l8 6 8-6"/></svg>
        Mở thiệp mời
      </button>
    </div>
  );
}

/* ---------- Sổ lưu bút (lời chúc) — lưu localStorage ---------- */
function Wishes() {
  const seed = [
    { name: 'Gia đình hai họ', msg: 'Chúc hai con trăm năm hạnh phúc, sắt son một đời.' },
  ];
  const [list, setList] = useState(() => {
    try { const s = JSON.parse(localStorage.getItem('wedding-wishes') || 'null'); return s && s.length ? s : seed; }
    catch { return seed; }
  });
  const [name, setName] = useState('');
  const [msg, setMsg] = useState('');

  const add = (e) => {
    e.preventDefault();
    if (!name.trim() || !msg.trim()) return;
    const next = [{ name: name.trim(), msg: msg.trim() }, ...list];
    setList(next);
    try { localStorage.setItem('wedding-wishes', JSON.stringify(next)); } catch {}
    setName(''); setMsg('');
  };

  return (
    <div className="wishes">
      <form className="wish-form" onSubmit={add}>
        <input className="rsvp-input" type="text" placeholder="Tên của bạn"
          value={name} onChange={(e) => setName(e.target.value)} required />
        <textarea className="rsvp-input wish-text" placeholder="Gửi lời chúc đến cô dâu chú rể..."
          rows={3} value={msg} onChange={(e) => setMsg(e.target.value)} required />
        <button type="submit" className="m-btn" style={{ width: '100%' }}>Gửi lời chúc</button>
      </form>
      <div className="wish-list">
        {list.map((w, i) => (
          <div className="wish-card" key={i}>
            <p className="wish-msg">“{w.msg}”</p>
            <p className="wish-name">— {w.name}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Thiệp chính ---------- */
function Invite() {
  const W = window.WED;
  const [opened, setOpened] = useState(false);
  const [coverGone, setCoverGone] = useState(false);
  const [musicSignal, setMusicSignal] = useState(0);
  const progressRef = useRef(null);

  // Thanh tiến trình cuộn — ghi thẳng style.width qua rAF (gộp khung hình),
  // KHÔNG cập nhật React state mỗi lần cuộn ⇒ mượt, không vẽ lại ô ảnh.
  useEffect(() => {
    document.body.classList.add('locked');
    let raf = 0;
    const update = () => {
      raf = 0;
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      const pct = max > 0 ? (h.scrollTop / max) * 100 : 0;
      if (progressRef.current) progressRef.current.style.width = pct + '%';
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    update();
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); if (raf) cancelAnimationFrame(raf); };
  }, []);

  const openInvite = () => {
    setOpened(true);
    document.body.classList.remove('locked');
    setMusicSignal((s) => s + 1);
    window.scrollTo({ top: 0 });
    // Gỡ bìa khỏi DOM sau khi mờ dần — chắc chắn không che nội dung
    setTimeout(() => setCoverGone(true), 1150);
  };

  const toNext = () => {
    const el = document.getElementById('after-hero');
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <div className="m-root">
      <div className="m-progress" ref={progressRef}></div>
      <window.Petals count={16} />
      {!coverGone && <Cover open={opened} onOpen={openInvite} />}

      {/* ---------- HERO — mở ra theo nhịp (cascade 0 → 680ms) ---------- */}
      <header className="hero">
        <window.Reveal delay={0}>
          <div className="hero-mono">{W.monogram}</div>
        </window.Reveal>
        <window.Reveal delay={140}>
          <p className="m-eyebrow" style={{ margin: 'clamp(20px,3vw,30px) 0' }}>Trân trọng kính mời</p>
        </window.Reveal>
        <window.Reveal delay={280}>
          <h1 className="m-names">
            <span className="ln">{W.groom}</span>
            <span className="m-amp">&amp;</span>
            <span className="ln">{W.bride}</span>
          </h1>
        </window.Reveal>
        <window.Reveal delay={420}>
          <p style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(16px,3vw,22px)', letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--ink-soft)', margin: 'clamp(24px,4vw,34px) 0 0' }}>{W.dateText}</p>
        </window.Reveal>
        <window.Reveal delay={540} style={{ width: '100%', marginTop: 'clamp(36px,5vw,56px)', display: 'flex', justifyContent: 'center' }}>
          <div className="hero-photo-arch hero-photo--xl">
            <ImgSlot id="hero-main" placeholder="Kéo ảnh cưới chính vào đây"
              style={{ display: 'block', width: '100%', height: '100%' }} />
          </div>
        </window.Reveal>
        <window.Reveal delay={680} style={{ marginTop: 'clamp(30px,4vw,46px)' }}>
          <div className="scroll-cue" onClick={toNext} style={{ cursor: 'pointer' }}>
            <span style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '.24em', textTransform: 'uppercase' }}>Cuộn xuống</span>
            <svg width="14" height="22" viewBox="0 0 14 22" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round"><path d="M7 1v17M2 13l5 5 5-5"/></svg>
          </div>
        </window.Reveal>
      </header>

      {/* ---------- LỜI MỜI ---------- */}
      <section id="after-hero" className="sec sec--paper">
        <div className="wrap wrap--narrow center">
          <window.Reveal>
            <window.Sprig size={44} color="var(--sage)" style={{ marginBottom: 22 }} />
            <p className="m-quote" style={{ color: 'var(--sage-deep)', marginBottom: 14 }}>“{W.quote}”</p>
            <p className="m-eyebrow" style={{ fontSize: 10, color: 'var(--ink-faint)' }}>{W.quoteAuthor}</p>
          </window.Reveal>
          <window.Reveal>
            <p className="m-body" style={{ marginTop: 'clamp(28px,4vw,40px)' }}>{W.invite}</p>
          </window.Reveal>
        </div>
      </section>

      {/* ---------- DẢI ẢNH 1 (điểm nhấn) ---------- */}
      <Band id="band-1" lab="Save the date" big="Hẹn ước trăm năm" sub={W.dateText} />

      {/* ---------- GIA ĐÌNH ---------- */}
      <section className="sec">
        <div className="wrap">
          <window.Reveal>
            <div className="family">
              <div className="center">
                <p className="m-eyebrow" style={{ marginBottom: 16 }}>Nhà Trai</p>
                {W.groomParents.map((n) => <p className="name" key={n}>{n}</p>)}
                <p className="m-body" style={{ marginTop: 14, fontSize: 'clamp(12px,2vw,14px)' }}>{W.groomAddress}</p>
              </div>
              <div className="vline"></div>
              <div className="center">
                <p className="m-eyebrow" style={{ marginBottom: 16 }}>Nhà Gái</p>
                {W.brideParents.map((n) => <p className="name" key={n}>{n}</p>)}
                <p className="m-body" style={{ marginTop: 14, fontSize: 'clamp(12px,2vw,14px)' }}>{W.brideAddress}</p>
              </div>
            </div>
          </window.Reveal>
        </div>
      </section>

      {/* ---------- ĐẾM NGƯỢC ---------- */}
      <section className="sec sec--mist">
        <div className="wrap center">
          <window.Reveal><LabelRule>Đếm ngược</LabelRule></window.Reveal>
          <window.Reveal>
            <h2 className="m-title" style={{ marginBottom: 'clamp(28px,4vw,44px)' }}>Đến ngày chung đôi</h2>
            <CountdownR />
            <p style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 'clamp(15px,2.6vw,19px)', color: 'var(--ink-soft)', marginTop: 'clamp(28px,4vw,40px)' }}>{W.dateLong}</p>
          </window.Reveal>
        </div>
      </section>

      {/* ---------- ALBUM ---------- */}
      <section className="sec">
        <div className="wrap center">
          <window.Reveal><LabelRule>Album</LabelRule></window.Reveal>
          <window.Reveal>
            <h2 className="m-title" style={{ marginBottom: 'clamp(26px,4vw,40px)' }}>Khoảnh khắc của chúng tôi</h2>
          </window.Reveal>
          <window.Reveal><GalleryR /></window.Reveal>
        </div>
      </section>

      {/* ---------- SỰ KIỆN ---------- */}
      <section className="sec sec--paper">
        <div className="wrap center">
          <window.Reveal><LabelRule>Sự kiện</LabelRule></window.Reveal>
          <window.Reveal>
            <div className="events">
              {[W.ceremony, W.party].map((e) => (
                <div className="event-card" key={e.label}>
                  <p className="m-eyebrow" style={{ marginBottom: 14 }}>{e.label}</p>
                  <p className="event-time">{e.time}</p>
                  <p className="m-body" style={{ margin: 0, fontSize: 'clamp(12px,2vw,14px)' }}>{e.note} · {W.weekday}, {W.day}/{W.month}/{W.year}</p>
                </div>
              ))}
            </div>
          </window.Reveal>
          <window.Reveal>
            <div style={{ marginTop: 'clamp(30px,4vw,44px)' }}>
              <p style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(20px,3.4vw,26px)', color: 'var(--ink)', margin: '0 0 8px', lineHeight: 1.35 }}>{W.venueFull}</p>
              <p className="m-body" style={{ margin: '0 0 2px' }}>{W.hall}</p>
              <p className="m-body" style={{ margin: 0 }}>{W.address}</p>
            </div>
          </window.Reveal>
        </div>
      </section>

      {/* ---------- BẢN ĐỒ ---------- */}
      <section className="sec">
        <div className="wrap center">
          <window.Reveal><LabelRule>Bản đồ</LabelRule></window.Reveal>
          <window.Reveal>
            <div className="map-frame">
              <iframe title="Bản đồ địa điểm" src={W.mapsEmbed} loading="lazy" referrerPolicy="no-referrer-when-downgrade"></iframe>
            </div>
            <div style={{ marginTop: 22 }}><window.MapButton /></div>
          </window.Reveal>
        </div>
      </section>

      {/* ---------- DẢI ẢNH 2 (điểm nhấn) ---------- */}
      <Band id="band-2" big={'“' + W.quote + '”'} />

      {/* ---------- SỔ LƯU BÚT ---------- */}
      <section className="sec sec--paper">
        <div className="wrap center">
          <window.Reveal><LabelRule>Sổ lưu bút</LabelRule></window.Reveal>
          <window.Reveal>
            <h2 className="m-title" style={{ marginBottom: 'clamp(26px,4vw,38px)' }}>Lời chúc yêu thương</h2>
          </window.Reveal>
          <window.Reveal><Wishes /></window.Reveal>
        </div>
      </section>

      {/* ---------- KẾT ---------- */}
      <section className="sec sec--deep">
        <div className="wrap center">
          <window.Reveal>
            <window.Sprig size={48} color="var(--sage-soft)" style={{ marginBottom: 22 }} />
            <p style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 'clamp(18px,3.4vw,26px)', lineHeight: 1.6, margin: '0 0 clamp(24px,4vw,36px)', color: 'var(--cream)' }}>{W.closing}</p>
            <h2 className="m-names" style={{ color: '#fff' }}>
              <span style={{ display: 'block', fontSize: 'clamp(36px,8.5vw,68px)', lineHeight: 1.12, whiteSpace: 'normal' }}>{W.groom} &amp; {W.bride}</span>
            </h2>
            <p style={{ fontFamily: 'var(--serif)', letterSpacing: '.2em', fontSize: 'clamp(13px,2.4vw,16px)', marginTop: 16, color: 'var(--sage-soft)', textTransform: 'uppercase' }}>{W.dateText}</p>
          </window.Reveal>
        </div>
      </section>

      <window.MusicPlayer fixed signal={musicSignal} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<Invite />);
